blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 4
250
| content_id
stringlengths 40
40
| detected_licenses
sequencelengths 0
58
| license_type
stringclasses 2
values | repo_name
stringlengths 5
107
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 185
values | visit_date
timestamp[us] | revision_date
timestamp[us] | committer_date
timestamp[us] | github_id
int64 15.7k
664M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 17
values | gha_event_created_at
timestamp[us] | gha_created_at
timestamp[us] | gha_language
stringclasses 68
values | src_encoding
stringclasses 27
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 6
9.36M
| extension
stringclasses 31
values | content
stringlengths 4
9.36M
| authors
sequencelengths 1
1
| author
stringlengths 0
73
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
35f7b3122f26844fda57d0b6d6de51b0c0065a52 | c517bd71f293a9875608cada7242a44e3d7e6808 | /ex17/ex17.c | d89d66e6f4e052cc8ed4517785bcc7471d1bead8 | [] | no_license | twistedlog/c-notes | 88856c254e0966e3c9b86997a73654c03e0300e0 | ebba6aa7f80f3432430469b44401ead14ffb5e7a | refs/heads/master | 2020-03-19T04:51:09.667766 | 2018-06-03T04:53:04 | 2018-06-03T04:53:04 | 135,874,606 | 0 | 0 | null | null | null | null | UTF-8 | C | false | false | 4,178 | c | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#define MAX_DATA 512
#define MAX_ROWS 100
// TODO check does malloc round off sizeof
struct Address {
int id;
int set;
char name[MAX_DATA];
char email[MAX_DATA];
};
struct Database {
struct Address rows[MAX_ROWS];
};
struct Connection {
FILE *file;
struct Database *db;
};
void die(const char *message) {
if (errno) {
perror(message);
} else {
printf("ERROR: %s\n", message);
}
exit(1);
}
void Database_load(struct Connection *conn) {
int rc = fread(conn->db, sizeof(struct Database), 1, conn->file);
if (rc != 1) {
die("Failed to load Database");
}
}
void Address_print(struct Address *addr){
printf("%d %s %s\n", addr->id, addr->name, addr->email);
}
struct Connection *Database_open(const char *filename, char mode){
struct Connection *conn = malloc(sizeof(struct Connection));
if (!conn) {
die("Memory Error");
}
conn->db = malloc(sizeof(struct Database));
if (!conn->db) {
die("Memory Error");
}
if (mode == 'c') {
/*
``w'' Truncate to zero length or create text file for writing.
The stream is positioned at the beginning of the file.
*/
conn->file = fopen(filename, "w");
} else {
conn->file = fopen(filename, "r+");
if (conn->file) {
Database_load(conn);
}
}
if (!conn->file) {
die("Failed to open database file");
}
return conn;
}
void Database_create(struct Connection *conn) {
int i = 0;
for (i=0; i<MAX_ROWS; i++){
struct Address addr = {.id = i,.set = 0 };
conn->db->rows[i] = addr;
}
}
void Database_write(struct Connection *conn) {
rewind(conn->file);
int rc = fwrite(conn->db, sizeof(struct Database), 1, conn->file);
if (rc != 1){
die("Failed to write to file");
}
rc = fflush(conn->file);
if (rc == -1) {
die("Cannot flush database");
}
}
void Database_get(struct Connection *conn, int id){
struct Address *addr = &conn->db->rows[id];
if (addr->set){
Address_print(addr);
} else {
die("ID is not set");
}
}
void Database_set(struct Connection *conn, int id, char *name, char *email) {
struct Address *addr = &conn->db->rows[id];
if (addr->set){
die("Alerady set, Delete it first");
}
addr->set = 1;
char *res = strncpy(addr->name, name, MAX_DATA);
if (!res) {
die("Name copy failed");
}
res = strncpy(addr->email, email, MAX_DATA);
if (!res) {
die("Email copy failed");
}
}
void Database_delete(struct Connection *conn, int id) {
struct Address addr = {.id = id, .set =0};
conn->db->rows[id] = addr;
}
void Database_list(struct Connection *conn){
int i = 0;
for (i=0; i<MAX_ROWS; i++) {
struct Address *row = &conn->db->rows[i];
if (row->set)
Address_print(row);
}
}
void Database_close(struct Connection *conn){
if (conn){
if (conn->file){
fclose(conn->file);
}
// TODO comment free conn->db and analyze in debugger or valgrind to find
// memory leaks
if (conn->db) {
free(conn->db);
}
free(conn);
}
}
int main(int argc, char *argv[]) {
if (argc < 3) {
die("USAGE: ex17 <dbfile> <action> [action params]");
}
char *filename = argv[1];
char action = argv[2][0];
struct Connection *conn = Database_open(filename, action);
int id=0;
if (argc > 3) id = atoi(argv[3]);
if (id >= MAX_ROWS) die("There's not that many records");
switch (action) {
case 'c':
Database_create(conn);
Database_write(conn);
break;
case 'g':
if (argc < 4) {
die("missing row argument");
}
Database_get(conn, id);
break;
case 's':
if (argc < 6)
die("Need id, name, email to set");
Database_set(conn, id, argv[4], argv[5]);
Database_write(conn);
break;
case 'd':
if (argc != 4)
die("row id to be deleted is needed");
Database_delete(conn, id);
Database_write(conn);
break;
case 'l':
Database_list(conn);
break;
default:
die("Invalid action: c=create, g=get, s=set, d=del, l=list");
}
Database_close(conn);
return 0;
}
| [
"[email protected]"
] | |
a0a92d3ca501ad192639cc0f6acb74a87d8b3d5c | d59f4db8d99186a314376fcbec871eb35c0fb347 | /Day10/ex03/ft_any.c | 067c0da111308e6415b14f75f194889ca33d8636 | [] | no_license | ymukmar/Wethinkcode_ | 354bc4d699c73824482909cfe13d416a8bc3a5e9 | 87466fe3627c19d0f63ea766ad10503913de6a88 | refs/heads/master | 2021-01-01T04:19:55.605120 | 2016-04-21T11:37:04 | 2016-04-21T11:37:04 | 56,409,157 | 2 | 0 | null | null | null | null | UTF-8 | C | false | false | 1,036 | c | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_any.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ymukmar <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2016/04/13 17:34:04 by ymukmar #+# #+# */
/* Updated: 2016/04/13 17:53:21 by ymukmar ### ########.fr */
/* */
/* ************************************************************************** */
int ft_any(char **tab, int (*f)(char*))
{
int i;
i = 0;
while (*tab != 0)
{
if (f(*(tab + 1)))
return (1);
i++;
}
return (0);
}
| [
"[email protected]"
] | |
82397e49d10b06b3b9bd7cd227a1a4e5b05b0e67 | 0fa443a65716c2295b590043af304b215973df2d | /SystemStarter/IPC.c | 2ba96fe81a6f414d426223e19aba18ab67de31d2 | [] | no_license | apple-opensource/Startup | ec31dc34419476c5d6b559ea183da92ee73899ac | 89d95e544b770a905b92ce7156dc5ad61092b541 | refs/heads/master | 2021-04-11T16:29:57.940621 | 2016-09-02T23:43:06 | 2016-09-02T23:43:06 | 249,036,976 | 0 | 1 | null | null | null | null | UTF-8 | C | false | false | 20,668 | c | /**
* IPC.c - System Starter IPC routines
* Wilfredo Sanchez | [email protected]
* Kevin Van Vechten | [email protected]
* $Apple$
**
* Copyright (c) 1999-2002 Apple Computer, Inc. All rights reserved.
*
* @APPLE_LICENSE_HEADER_START@
*
* Portions Copyright (c) 1999 Apple Computer, Inc. All Rights
* Reserved. This file contains Original Code and/or Modifications of
* Original Code as defined in and that are subject to the Apple Public
* Source License Version 1.1 (the "License"). You may not use this file
* except in compliance with the License. Please obtain a copy of the
* License at http://www.apple.com/publicsource and read it before using
* this file.
*
* The Original Code and all software distributed under the License are
* distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE OR NON- INFRINGEMENT. Please see the
* License for the specific language governing rights and limitations
* under the License.
*
* @APPLE_LICENSE_HEADER_END@
**/
#include <sys/wait.h>
#include <mach/mach.h>
#include <mach/message.h>
#include <mach/mach_error.h>
#include <servers/bootstrap.h>
#include <CoreFoundation/CoreFoundation.h>
#include "main.h"
#include "Log.h"
#include "IPC.h"
#include "StartupItems.h"
#include "SystemStarter.h"
#include "SystemStarterIPC.h"
/* Structure to pass StartupContext and anItem to the termination handler. */
typedef struct TerminationContextStorage {
StartupContext aStartupContext;
CFMutableDictionaryRef anItem;
} *TerminationContext;
/**
* A CFMachPort invalidation callback that records the termination of
* a startup item task. Stops the current run loop to give system_starter
* another go at running items.
**/
static void startupItemTerminated (CFMachPortRef aMachPort, void *anInfo)
{
TerminationContext aTerminationContext = (TerminationContext) anInfo;
if (aMachPort)
{
mach_port_deallocate(mach_task_self(), CFMachPortGetPort(aMachPort));
}
if (aTerminationContext && aTerminationContext->anItem)
{
pid_t aPID = 0;
pid_t rPID = 0;
int aStatus = 0;
CFMutableDictionaryRef anItem = aTerminationContext->anItem;
StartupContext aStartupContext = aTerminationContext->aStartupContext;
/* Get the exit status */
if (anItem)
{
aPID = StartupItemGetPID(anItem);
if (aPID > 0)
rPID = waitpid(aPID, &aStatus, WNOHANG);
}
if (aStartupContext)
{
--aStartupContext->aRunningCount;
/* Record the item's status */
if (aStartupContext->aStatusDict)
{
StartupItemExit(aStartupContext->aStatusDict, anItem, (WIFEXITED(aStatus) && WEXITSTATUS(aStatus) == 0));
if (aStatus)
{
warning(CFSTR("%@ (%d) did not complete successfully.\n"), CFDictionaryGetValue(anItem, CFSTR("Description")), aPID);
}
else
{
if (gDebugFlag) debug(CFSTR("Finished %@ (%d)\n"), CFDictionaryGetValue(anItem, CFSTR("Description")), aPID);
}
displayProgress(aStartupContext->aDisplayContext, ((float)CFDictionaryGetCount(aStartupContext->aStatusDict)/((float)aStartupContext->aServicesCount + 1.0)));
}
/* If the item failed to start, then add it to the failed list */
if (WEXITSTATUS(aStatus) || WTERMSIG(aStatus) || WCOREDUMP(aStatus))
{
CFDictionarySetValue(anItem, kErrorKey, kErrorReturnNonZero);
AddItemToFailedList(aStartupContext, anItem);
}
/* Remove the item from the waiting list regardless if it was successful or it failed. */
RemoveItemFromWaitingList(aStartupContext, anItem);
}
}
if (aTerminationContext) free(aTerminationContext);
/* Stop the current run loop so the system_starter engine will cycle and try to start any newly eligible items */
CFRunLoopStop(CFRunLoopGetCurrent());
}
void MonitorStartupItem (StartupContext aStartupContext, CFMutableDictionaryRef anItem)
{
pid_t aPID = StartupItemGetPID(anItem);
if (anItem && aPID > 0)
{
mach_port_t aPort;
kern_return_t aResult;
CFMachPortContext aContext;
CFMachPortRef aMachPort;
CFRunLoopSourceRef aSource;
TerminationContext aTerminationContext = (TerminationContext) malloc(sizeof(struct TerminationContextStorage));
aTerminationContext->aStartupContext = aStartupContext;
aTerminationContext->anItem = anItem;
aContext.version = 0;
aContext.info = aTerminationContext;
aContext.retain = 0;
aContext.release = 0;
if ((aResult = task_for_pid(mach_task_self(), aPID, &aPort)) != KERN_SUCCESS)
goto out_bad;
if (!(aMachPort = CFMachPortCreateWithPort(NULL, aPort, NULL, &aContext, NULL)))
goto out_bad;
if (!(aSource = CFMachPortCreateRunLoopSource(NULL, aMachPort, 0))) {
CFRelease(aMachPort);
goto out_bad;
}
CFMachPortSetInvalidationCallBack(aMachPort, startupItemTerminated);
CFRunLoopAddSource(CFRunLoopGetCurrent(), aSource, kCFRunLoopCommonModes);
CFRelease(aSource);
CFRelease(aMachPort);
return;
out_bad:
/* The assumption is something failed, the task already terminated. */
startupItemTerminated(NULL, aTerminationContext);
}
}
/**
* Returns a reference to an item based on tokens passed in an IPC message.
* This is useful for figuring out which item the message came from.
*
* Currently two tokens are supported:
* kIPCProcessIDKey - the pid of the running startup script
* kIPCServiceNameKey - a name of a service that the item provides. This
* takes precedence over the pid key when both are present.
**/
static CFMutableDictionaryRef itemFromIPCMessage (StartupContext aStartupContext, CFDictionaryRef anIPCMessage)
{
CFMutableDictionaryRef anItem = NULL;
if (aStartupContext && anIPCMessage)
{
CFStringRef aServiceName = CFDictionaryGetValue(anIPCMessage, kIPCServiceNameKey);
CFIndex aPID = 0;
CFNumberRef aPIDNumber = CFDictionaryGetValue(anIPCMessage, kIPCProcessIDKey);
if (aServiceName && CFGetTypeID(aServiceName) == CFStringGetTypeID())
{
anItem = StartupItemListGetProvider(aStartupContext->aWaitingList, aServiceName);
}
else if (aPIDNumber &&
CFGetTypeID(aPIDNumber) == CFNumberGetTypeID() &&
CFNumberGetValue(aPIDNumber, kCFNumberCFIndexType, &aPID) )
{
anItem = StartupItemWithPID(aStartupContext->aWaitingList, aPID);
}
}
return anItem;
}
/**
* Displays a message on the console.
* aConsoleMessage will be localized according to the dictionary in the specified item.
* Running tems may be specified by their current process id. Items may also be specified
* by one of the service names they provide.
**/
static void consoleMessage (StartupContext aStartupContext, CFDictionaryRef anIPCMessage)
{
if (aStartupContext && anIPCMessage)
{
CFStringRef aConsoleMessage = CFDictionaryGetValue(anIPCMessage, kIPCConsoleMessageKey);
if (aConsoleMessage && CFGetTypeID(aConsoleMessage) == CFStringGetTypeID())
{
CFStringRef aLocalizedMessage = NULL;
CFDictionaryRef anItem = itemFromIPCMessage(aStartupContext, anIPCMessage);
if (anItem)
{
aLocalizedMessage = StartupItemCreateLocalizedString(anItem, aConsoleMessage);
}
if (!aLocalizedMessage) aLocalizedMessage = CFRetain(aConsoleMessage);
displayStatus(aStartupContext->aDisplayContext, aLocalizedMessage);
CFRelease(aLocalizedMessage);
}
}
}
/**
* Records the success or failure or a particular service.
* If no service name is specified, but a pid is, then all services provided
* by the item are flagged.
**/
static void statusMessage (StartupContext aStartupContext, CFDictionaryRef anIPCMessage)
{
if (anIPCMessage && aStartupContext && aStartupContext->aStatusDict)
{
CFMutableDictionaryRef anItem = itemFromIPCMessage(aStartupContext, anIPCMessage);
CFStringRef aServiceName = CFDictionaryGetValue(anIPCMessage, kIPCServiceNameKey);
CFBooleanRef aStatus = CFDictionaryGetValue(anIPCMessage, kIPCStatusKey);
if (anItem && aStatus &&
CFGetTypeID(aStatus) == CFBooleanGetTypeID() &&
(!aServiceName || CFGetTypeID(aServiceName) == CFStringGetTypeID()))
{
StartupItemSetStatus(aStartupContext->aStatusDict, anItem, aServiceName, CFBooleanGetValue(aStatus), TRUE);
displayProgress(aStartupContext->aDisplayContext, ((float)CFDictionaryGetCount(aStartupContext->aStatusDict)/((float)aStartupContext->aServicesCount + 1.0)));
}
}
}
/**
* Queries one of several configuration settings.
*/
static CFDataRef queryConfigSetting (StartupContext aStartupContext, CFDictionaryRef anIPCMessage)
{
char* aValue = "";
if (anIPCMessage)
{
CFStringRef aSetting = CFDictionaryGetValue(anIPCMessage, kIPCConfigSettingKey);
if (aSetting && CFGetTypeID(aSetting) == CFStringGetTypeID())
{
if (CFEqual(aSetting, kIPCConfigSettingVerboseFlag))
{
aValue = gVerboseFlag ? "-YES-" : "-NO-";
}
else if (CFEqual(aSetting, kIPCConfigSettingSafeBoot))
{
aValue = gSafeBootFlag ? "-YES-" : "-NO-";
}
else if (CFEqual(aSetting, kIPCConfigSettingNetworkUp))
{
Boolean aNetworkUpFlag = FALSE;
if (aStartupContext && aStartupContext->aStatusDict)
{
aNetworkUpFlag = CFDictionaryContainsKey(aStartupContext->aStatusDict, CFSTR("Network"));
}
aValue = aNetworkUpFlag ? "-YES-" : "-NO-";
}
}
}
return CFDataCreate(NULL, aValue, strlen(aValue) + 1); /* aValue + null */
}
/**
* Loads the SystemStarter display bundle at the specified path.
* A no-op if SystemStarter is not starting in graphical mode.
**/
static void loadDisplayBundle (StartupContext aStartupContext, CFDictionaryRef anIPCMessage)
{
if (!gVerboseFlag && anIPCMessage && aStartupContext)
{
CFStringRef aBundlePath = CFDictionaryGetValue(anIPCMessage, kIPCDisplayBundlePathKey);
if (aBundlePath && CFGetTypeID(aBundlePath) == CFStringGetTypeID())
{
extern void LoadDisplayPlugIn(CFStringRef);
if (aStartupContext->aDisplayContext)
freeDisplayContext(aStartupContext->aDisplayContext);
LoadDisplayPlugIn(aBundlePath);
aStartupContext->aDisplayContext = initDisplayContext();
{
CFStringRef aLocalizedString = LocalizedString(aStartupContext->aResourcesBundlePath, kWelcomeToMacintoshKey);
if (aLocalizedString)
{
displayStatus(aStartupContext->aDisplayContext, aLocalizedString);
displayProgress(aStartupContext->aDisplayContext, ((float)CFDictionaryGetCount(aStartupContext->aStatusDict)/((float)aStartupContext->aServicesCount + 1.0)));
CFRelease(aLocalizedString);
}
}
if (gSafeBootFlag)
{
CFStringRef aLocalizedString = LocalizedString(aStartupContext->aResourcesBundlePath, kSafeBootKey);
if (aLocalizedString)
{
(void) displaySafeBootMsg(aStartupContext->aDisplayContext, aLocalizedString);
CFRelease(aLocalizedString);
}
}
}
}
}
/**
* Unloads the SystemStarter display bundle.
* A no-op if SystemStarter is not starting in graphical mode,
* or if no display bundle is loaded.
**/
static void unloadDisplayBundle (StartupContext aStartupContext, CFDictionaryRef anIPCMessage)
{
aStartupContext->aQuitOnNotification = 0;
if (!gVerboseFlag && aStartupContext)
{
extern void UnloadDisplayPlugIn();
if (aStartupContext->aDisplayContext)
freeDisplayContext(aStartupContext->aDisplayContext);
UnloadDisplayPlugIn();
/* Use the default text display again. */
aStartupContext->aDisplayContext = initDisplayContext();
CFRunLoopStop(CFRunLoopGetCurrent());
}
}
static void* handleIPCMessage (void* aMsgParam, CFIndex aMessageSize, CFAllocatorRef anAllocator, void* aMachPort)
{
SystemStarterIPCMessage* aMessage = (SystemStarterIPCMessage*) aMsgParam;
SystemStarterIPCMessage* aReplyMessage = NULL;
CFDataRef aResult = NULL;
CFDataRef aData = NULL;
if (aMessage->aHeader.msgh_bits & MACH_MSGH_BITS_COMPLEX)
{
warning(CFSTR("Ignoring out-of-line IPC message.\n"));
return NULL;
}
else
{
mach_msg_security_trailer_t* aSecurityTrailer = (mach_msg_security_trailer_t*)
((uint8_t*)aMessage + round_msg(sizeof(SystemStarterIPCMessage) + aMessage->aByteLength));
/* CFRunLoop includes the format 0 message trailer with the passed message. */
if (aSecurityTrailer->msgh_trailer_type == MACH_MSG_TRAILER_FORMAT_0 &&
aSecurityTrailer->msgh_sender.val[0] != 0)
{
warning(CFSTR("Ignoring IPC message sent from uid %d\n."), aSecurityTrailer->msgh_sender.val[0]);
return NULL;
}
}
if (aMessage->aProtocol != kIPCProtocolVersion)
{
warning(CFSTR("Unsupported IPC protocol version number: %d. Message ignored.\n"), aMessage->aProtocol);
return NULL;
}
aData = CFDataCreateWithBytesNoCopy(NULL,
(uint8_t*)aMessage + sizeof(SystemStarterIPCMessage),
aMessage->aByteLength,
kCFAllocatorNull);
/*
* Dispatch the IPC message.
*/
if (aData)
{
StartupContext aStartupContext = NULL;
CFStringRef anErrorString = NULL;
CFDictionaryRef anIPCMessage = (CFDictionaryRef) CFPropertyListCreateFromXMLData(NULL, aData, kCFPropertyListImmutable, &anErrorString);
if (gDebugFlag == 2) debug(CFSTR("\nIPC message = %@\n"), anIPCMessage);
if (aMachPort)
{
CFMachPortContext aMachPortContext;
CFMachPortGetContext((CFMachPortRef)aMachPort, &aMachPortContext);
aStartupContext = (StartupContext)aMachPortContext.info;
}
if (anIPCMessage && CFGetTypeID(anIPCMessage) == CFDictionaryGetTypeID())
{
/* switch on the type of the IPC message */
CFStringRef anIPCMessageType = CFDictionaryGetValue(anIPCMessage, kIPCMessageKey);
if (anIPCMessageType && CFGetTypeID(anIPCMessageType) == CFStringGetTypeID())
{
if (CFEqual(anIPCMessageType, kIPCConsoleMessage))
{
consoleMessage(aStartupContext, anIPCMessage);
}
else if (CFEqual(anIPCMessageType, kIPCStatusMessage))
{
statusMessage(aStartupContext, anIPCMessage);
}
else if (CFEqual(anIPCMessageType, kIPCQueryMessage))
{
aResult = queryConfigSetting(aStartupContext, anIPCMessage);
}
else if (CFEqual(anIPCMessageType, kIPCLoadDisplayBundleMessage))
{
loadDisplayBundle(aStartupContext, anIPCMessage);
}
else if (CFEqual(anIPCMessageType, kIPCUnloadDisplayBundleMessage))
{
unloadDisplayBundle(aStartupContext, anIPCMessage);
}
}
}
else
{
error(CFSTR("Unable to parse IPC message: %@\n"), anErrorString);
}
CFRelease(aData);
}
else
{
error(CFSTR("Out of memory. Could not allocate space for IPC message.\n"));
}
/*
* Generate a Mach message for the result data.
*/
if (!aResult) aResult = CFDataCreateWithBytesNoCopy(NULL, "", 1, kCFAllocatorNull);
if (aResult)
{
CFIndex aDataSize = CFDataGetLength(aResult);
CFIndex aReplyMessageSize = round_msg(sizeof(SystemStarterIPCMessage) + aDataSize + 3);
aReplyMessage = CFAllocatorAllocate(kCFAllocatorSystemDefault, aReplyMessageSize, 0);
if (aReplyMessage)
{
aReplyMessage->aHeader.msgh_id = -1 * (SInt32)aMessage->aHeader.msgh_id;
aReplyMessage->aHeader.msgh_size = aReplyMessageSize;
aReplyMessage->aHeader.msgh_remote_port = aMessage->aHeader.msgh_remote_port;
aReplyMessage->aHeader.msgh_local_port = MACH_PORT_NULL;
aReplyMessage->aHeader.msgh_reserved = 0;
aReplyMessage->aHeader.msgh_bits = MACH_MSGH_BITS(MACH_MSG_TYPE_MOVE_SEND_ONCE, 0);
aReplyMessage->aBody.msgh_descriptor_count = 0;
aReplyMessage->aProtocol = kIPCProtocolVersion;
aReplyMessage->aByteLength = CFDataGetLength(aResult);
memmove((uint8_t*)aReplyMessage + sizeof(SystemStarterIPCMessage),
CFDataGetBytePtr(aResult),
CFDataGetLength(aResult));
}
CFRelease(aResult);
}
if (!aReplyMessage)
{
error(CFSTR("Out of memory. Could not allocate IPC result.\n"));
}
return aReplyMessage;
}
static mach_port_t getIPCPort(void* anInfo)
{
return anInfo ? CFMachPortGetPort((CFMachPortRef)anInfo) : MACH_PORT_NULL;
}
CFRunLoopSourceRef CreateIPCRunLoopSource(CFStringRef aPortName, StartupContext aStartupContext)
{
CFRunLoopSourceRef aSource = NULL;
CFMachPortRef aMachPort = NULL;
CFMachPortContext aContext;
kern_return_t aKernReturn = KERN_FAILURE;
aContext.version = 0;
aContext.info = (void*) aStartupContext;
aContext.retain = 0;
aContext.release = 0;
aContext.copyDescription = 0;
aMachPort = CFMachPortCreate(NULL, NULL, &aContext, NULL);
if (aMachPort && aPortName)
{
CFIndex aPortNameLength = CFStringGetLength(aPortName);
CFIndex aPortNameSize = CFStringGetMaximumSizeForEncoding(aPortNameLength, kCFStringEncodingUTF8) + 1;
uint8_t *aBuffer = CFAllocatorAllocate(NULL, aPortNameSize, 0);
if (aBuffer && CFStringGetCString(aPortName,
aBuffer,
aPortNameSize,
kCFStringEncodingUTF8))
{
mach_port_t aBootstrapPort;
task_get_bootstrap_port(mach_task_self(), &aBootstrapPort);
aKernReturn = bootstrap_register(aBootstrapPort, aBuffer, CFMachPortGetPort(aMachPort));
}
if (aBuffer) CFAllocatorDeallocate(NULL, aBuffer);
}
if (aMachPort && aKernReturn == KERN_SUCCESS)
{
CFRunLoopSourceContext1 aSourceContext;
aSourceContext.version = 1;
aSourceContext.info = aMachPort;
aSourceContext.retain = CFRetain;
aSourceContext.release = CFRelease;
aSourceContext.copyDescription = CFCopyDescription;
aSourceContext.equal = CFEqual;
aSourceContext.hash = CFHash;
aSourceContext.getPort = getIPCPort;
aSourceContext.perform = (void*)handleIPCMessage;
aSource = CFRunLoopSourceCreate(NULL, 0, (CFRunLoopSourceContext*)&aSourceContext);
}
if (aMachPort && (!aSource || aKernReturn != KERN_SUCCESS))
{
CFMachPortInvalidate(aMachPort);
CFRelease(aMachPort);
aMachPort = NULL;
}
return aSource;
}
| [
"[email protected]"
] | |
74caccab28b250ce0b3c90b516ab15fb2b943d95 | 39b561c75833c3971149085f68db733b13e08f62 | /file_progs/open.c | 425a9d253a32eb25f5e7657c51dc03da9d8091f8 | [] | no_license | bharatmazire/LinuxSystemProgramming | e1d19794b17902ba584c3dc25eeb843c31a0e63c | d6eab23b872b7ad68d589c400f46f733135ec846 | refs/heads/master | 2021-09-04T11:42:24.182750 | 2018-01-18T11:00:27 | 2018-01-18T11:00:27 | 105,343,944 | 0 | 0 | null | null | null | null | UTF-8 | C | false | false | 659 | c | #include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<string.h>
#include<fcntl.h>
#include<errno.h>
int main(int argc,char **argv)
{
int ret;
int fd;
if(argc!=3)
{
printf("usage : %s <file_path> <message>\n",argv[0]);
exit(-1);
}
ret = access(argv[1],F_OK);
if( 0 != ret )
{
fd = open(argv[1],O_CREAT|O_WRONLY,0666);
}
else
{
fd = open(argv[1],O_APPEND | O_WRONLY);
}
if ( -1 == fd )
{
printf("file open failed. Error = %s \n",strerror(errno));
return -1;
}
int length = strlen(argv[2]);
ret = write(fd,argv[2],length);
if(ret != length)
{
printf("Error while writing a file");
close(fd);
}
return -1;
}
| [
"[email protected]"
] | |
eb2c5fdf8adf05072bf6d2779767aec42e2447fa | 1d9da947e69680e02c7e48792c9ef16b1b7c1ac2 | /IDA/generate_nasm.idc | d64b1f3fd966d88d196c0f5a5434852f9c5829a1 | [] | no_license | w3tutorials/Firmware-Analysis | 99dd41f87bd6b823ef9cd698de1f522e8466ea93 | 11b31e2682bb4ca945b431d7b57a2623c06778ea | refs/heads/master | 2016-09-06T12:39:23.573828 | 2015-02-07T10:08:06 | 2015-02-07T10:08:06 | 30,312,267 | 2 | 0 | null | null | null | null | UTF-8 | C | false | false | 3,994 | idc | /*
Copyright (c) 2008 Chris Eagle (cseagle at gmail d0t c0m)
*/
// Edited by Charalambos Konstantinou, January 2015
/*script to dump the current (as defined by cursor location) function to the output window using mostly nasm compatible syntax. You could potentially modify to save output to a file and iterate over every function in your database.*/
#include <idc.idc>
static formatOperand(addr, num) {
auto op, type, ptr, seg, var, idx, ch;
seg = "";
type = GetOpType(addr, num);
op = GetOpnd(addr, num);
if (op == "") {
return op;
}
if ((ptr = strstr(op, " ptr ")) != -1) {
op = substr(op, 0, ptr) + substr(op, ptr + 4, -1);
}
if ((ptr = strstr(op, "offset ")) == 0) {
op = substr(op, ptr + 7, -1);
}
if ((ptr = strstr(op, "large ")) == 0) {
op = substr(op, ptr + 6, -1);
}
if ((ptr = strstr(op, "ds:")) != -1) {
op = substr(op, 0, ptr) + substr(op, ptr + 3, -1);
}
if ((ptr = strstr(op, ":")) != -1) {
seg = substr(op, ptr - 2, ptr + 1);
op = substr(op, 0, ptr - 2) + substr(op, ptr + 1, -1);
}
if (type == 2) {
if ((ptr = strstr(op, "[")) == -1) {
op = "[" + op + "]";
}
}
else if (type == 4) {
ptr = strstr(op, "[");
if (ptr > 0) {
idx = ptr - 1;
var = "";
while (idx >= 0) {
ch = substr(op, idx, idx + 1);
if (ch == " ") break;
var = ch + var;
idx = idx - 1;
}
if (var != "") {
op = substr(op, 0, idx + 1) + "[" + var + "+" + substr(op, ptr + 1, -1);
}
}
}
if (seg != "") {
if ((ptr = strstr(op, "[")) != -1) {
op = substr(op, 0, ptr + 1) + seg + substr(op, ptr + 1, -1);
}
}
return op;
}
static main() {
auto addr, funcEnd, funcStart, name, line;
auto fname, op0, op1, op0Type, op1Type, ptr;
auto func, mnem, oper0, oper1, disp;
auto minEA, maxEA;
minEA = MinEA();
maxEA = MaxEA();
funcStart = GetFunctionAttr(ScreenEA(), FUNCATTR_START);
funcEnd = GetFunctionAttr(ScreenEA(), FUNCATTR_END);
fname = GetFunctionName(funcStart);
Message("USE32\n\n");
Message("section .text\n\n");
Message("global _%s\n\n", fname);
Message("_%s:\n", fname);
for (addr = funcStart; addr != BADADDR; addr = NextHead(addr, funcEnd)) {
if (addr != funcStart) {
name = NameEx(addr, addr);
if (name != "") {
Message("%s:\n", name);
}
}
op0 = 0;
op1 = 0;
op0Type = GetOpType(addr, 0);
op1Type = GetOpType(addr, 1);
if (op0Type == 3 || op0Type == 4) {
disp = GetOperandValue(addr, 0);
if (disp >= minEA && disp <= maxEA) {
}
else {
op0 = OpNumber(addr, 0);
}
}
if (op1Type == 3 || op1Type == 4) {
disp = GetOperandValue(addr, 1);
if (disp >= minEA && disp <= maxEA) {
}
else {
op0 = OpNumber(addr, 1);
}
}
line = GetDisasm(addr);
mnem = GetMnem(addr);
oper0 = formatOperand(addr, 0);
oper1 = formatOperand(addr, 1);
if (mnem == "call") {
if (op0Type >= 5 && op0Type <= 7) {
if (strstr(oper0, "_") != 0) {
oper0 = "_" + oper0;
}
}
}
if (oper0 == "" && oper1 == "") {
if (strstr(line, mnem) != 0) {
mnem = line;
}
line = form("%-8s", mnem);
}
else if (oper1 == "") {
line = form("%-7s %s", mnem, oper0);
}
else if (oper0 == "") {
line = form("%-7s %s", mnem, oper1);
}
else {
line = form("%-7s %s, %s", mnem, oper0, oper1);
}
Message(" %s\n", line);
if (op0) {
OpStkvar(addr, 0);
}
if (op1) {
OpStkvar(addr, 1);
}
}
}
| [
"[email protected]"
] | |
0c0f99fccc27df80060222c547dea4040c3d5733 | 9d4c0638a83a85b7b0be6744f38f370c093f25e5 | /ops/logical_ops.c | 7a56f6f6f384decd9f533c327ac1297af94c198b | [] | no_license | amit1952/c_projects | a269ebbb46287224f7dadd759d689c953a5734cc | df6fc74b245c5d0f469dcd8fd808b1d27c3cd24c | refs/heads/master | 2022-12-03T19:24:46.921824 | 2020-08-21T03:26:59 | 2020-08-21T03:26:59 | 279,755,498 | 0 | 0 | null | null | null | null | UTF-8 | C | false | false | 1,376 | c | /*
* Creator: Amitava Das Gupta
* Date: 20/07/2010
*/
#include <stdio.h>
#include <stdbool.h>
int main() {
printf("OR (||) Operations.\n");
_Bool a = true;
_Bool b = false;
_Bool result;
result = a || b;
printf("a = %d, b = %d\n", a, b);
printf("The result of a || b = %d\n", result);
a = true;
b = true;
result = a || b;
printf("a = %d, b = %d\n", a, b);
printf("The result of a || b = %d\n", result);
a = false;
b = false;
result = a || b;
printf("a = %d, b = %d\n", a, b);
printf("The result of a || b = %d\n", result);
a = false;
b = true;
result = a || b;
printf("a = %d, b = %d\n", a, b);
printf("The result of a || b = %d\n", result);
printf("\nAND (&&) Operations.\n");
a = true;
b = true;
result = a && b;
printf("a = %d, b = %d\n", a, b);
printf("The result of a && b = %d\n", result);
a = true;
b = false;
result = a && b;
printf("a = %d, b = %d\n", a, b);
printf("The result of a && b = %d\n", result);
a = false;
b = false;
result = a && b;
printf("a = %d, b = %d\n", a, b);
printf("The result of a && b = %d\n", result);
a = false;
b = true;
result = a && b;
printf("a = %d, b = %d\n", a, b);
printf("The result of a && b = %d\n", result);
return 0;
}
| [
"[email protected]"
] | |
9ac42847714df72425529f0f781b30b77010491b | 5901ffe091ffc38ab87fce5a83360fce4e4423d0 | /func.c | 496d6edbcbb59c6907c2fc97385cb853599ac436 | [] | no_license | Zhmur-Amir/Zadacha3. | 0dc667c1027c2774713f271d6b12bee881f7bf95 | b3c9d505f71af4a0256248d9d07c2e5445088da1 | refs/heads/master | 2022-04-26T20:01:26.908286 | 2020-04-30T13:49:43 | 2020-04-30T13:49:43 | 260,224,104 | 0 | 0 | null | null | null | null | UTF-8 | C | false | false | 2,508 | c | #include "func.h"
int func(int** arr, int* n, int* len_arr)
{
int summa=0, kolvo=0, flag=0,s=0, sred=0;
int temp_len=0, leng;
int* temp_arr;
for(int i=0; i<*n; i++ )
{
kolvo=kolvo+len_arr[i];
}
printf("kolvo=%d\n", kolvo);
for (int i=0; i<*n; i++)
{
for(int j=0; j<len_arr[i]; j++)
{
summa=summa+arr[i][j];
}
}
printf("summa=%d\n", summa);
if (summa%kolvo!=0)
{
return 0;
}
else {}
sred=summa/kolvo;
printf("sred=%d\n", sred);
for (int i=0; i<*n; i++)
{
for(int j=0; j<len_arr[i]; j++)
{
if (arr[i][j]==sred)
{
flag=1;
s=i;
}
else{}
}
if(flag!=0)break;
}
if(flag==0) {
return 2;
}
else
{
temp_arr = (int*)malloc(0*sizeof(int));
for (int d = s; d < (*n-1); d++)
{
temp_len = len_arr[d];
temp_arr = (int*)realloc(temp_arr, temp_len*sizeof(int));
for (int e = 0; e < temp_len; e++)
{
temp_arr[e] = arr[d][e];
}
arr[d] = (int*)realloc(arr[d], len_arr[d+1]*sizeof(int));
for (int j = 0; j < len_arr[d+1]; j++)
{
arr[d][j] = arr[d+1][j];
}
arr[d+1] = (int*)realloc(arr[d+1], temp_len*sizeof(int));
for (int f = 0; f < temp_len; f++)
{
arr[d+1][f] = temp_arr[f];
}
}
*n = *n-1;
arr = (int**)realloc(arr, (*n)*sizeof(int*));
for (int p=s; p<*n; p++)
{
leng=len_arr[p];
len_arr[p]=len_arr[p+1];
len_arr[p+1]=leng;
}
len_arr=(int*)realloc(len_arr, (*n)*sizeof(int));
free(temp_arr);
return 0;
}
}
void Autotest(void)
{
int **testarr;
int *lenarr;
int n= 3, m= 3;
testarr = (int**)malloc(3*sizeof(int*));
for (int k=0; k < 3; k++)
{
testarr[k] = (int*)malloc(3*sizeof(int));
for (int g=0; g < 3; g++)
{
testarr[k][g] = 1;
}
}
lenarr = (int*)malloc(3*sizeof(int));
for (int j = 0; j < 3; j++)
{
lenarr[j] = 3;
}
func(testarr, &n, lenarr);
if ((testarr[0][0] == 1)&&(testarr[1][0] == 1))
{
printf("Passed...respect+\n");
}
else
{
printf("Failed...\n");
}
for(int p=0; p < 2; p++)
{
free(testarr[p]);
}
free(testarr);
free(lenarr);
}
| [
"[email protected]"
] | |
36ce8adc34d7888a99b91f972beb118e04ae3c97 | 4290001c026a8014d87c1acd5cc613a5ffd3ce1e | /Tema2/fct_stiva.c | 47e939392784b118963716de1e10986378cb00ef | [] | no_license | albertchirila/SD | 8c2f493176fc06fb18bde880858d202f1937bd8f | a3c8ef9ce3966ef4021f69a81537b5ac9ec98714 | refs/heads/main | 2023-02-12T22:05:12.771262 | 2021-01-14T15:05:56 | 2021-01-14T15:05:56 | 329,649,552 | 0 | 0 | null | null | null | null | UTF-8 | C | false | false | 2,028 | c | /* NUME: CHIRILA ALBERT
GRUPA: 314CB */
#include "tema2.h"
/* functie initializare stiva */
void *InitS(size_t d)
{
TStiva *s;
s = (TStiva*)malloc(sizeof(TStiva)); /* se aloca stiva */
if(!s) return NULL; /* se verifica alocarea */
s->dim =d;
s->vf = NULL;
return (void*)s;
}
/* functie care verifica daca stiva este vida */
int VidaS(void *s)
{
if(((TStiva*)s)->vf==NULL) return 1;
return 0;
}
/* functie care introduce element in stiva */
void *Push(void *s, void *ae, size_t d)
{
TLG aux = (TLG)malloc(sizeof(TCelula));
if(!aux) return NULL; /* se verifica alocarea */
aux->info = (Proces*)malloc(d);
if(!aux->info) /* se verifica alocarea */
{
free(aux);
return NULL;
}
if(VidaS(s)==1)
{
((TStiva*)s)->vf=aux;
aux->urm=NULL;
memcpy(aux->info, ae, d); /* se copiaza informatia la adresa ae */
return (void*)s;
}
memcpy(aux->info, ae, d); /* se copiaza informatia la adresa ae */
aux->urm=((TStiva*)s)->vf;
((TStiva*)s)->vf=aux; /* se insereaza la inceput */
return (void*)s;
}
/* functie care extrage un element din varful stivei */
TLG Pop(void *s)
{
TLG aux;
int x = NrElS(s);
if(x==1)
{
aux = ((TStiva*)s)->vf;
((TStiva*)s)->vf=NULL;
return aux;
}
/* se extrage elemntu din varful stivei */
aux = ((TStiva*)s)->vf;
((TStiva*)s)->vf=aux->urm;
return aux;
}
/* functie care rastoarna stiva */
void *RastoarnaS(void *s, size_t d)
{
TLG aux;
TCoada *c;
c = InitC(sizeof(TCoada));
if(!c) return 0;
while(VidaS(s) != 1)
{
aux = Pop(s);
/* se foloseste coada auxiliara */
c = IntrQ(c, (Proces*)aux->info);
}
while(VidaC(c) != 1)
{
aux = ExtrQ(c);
s = Push(s, (Proces*)aux->info, d);
}
return (void*)s;
}
/* functie care concateneaza stiva s2 si stiva vida s1 */
void *ConcatS(void *s1, void *s2)
{
if(VidaS(s1)==1)
{
((TStiva*)s1)->vf = ((TStiva*)s2)->vf;
}
return (void*)s1;
}
/* functie care numara elementele stivei */
int NrElS(void *s)
{
int n=0;
TLG aux;
aux = ((TStiva*)s)->vf;
while(aux)
{
aux=aux->urm;
n++;
}
return n;
}
| [
"[email protected]"
] | |
ed786acb197aab102e743de788c47b51954015ec | d05cbc0f8084b047c8b7fbef8391b2e392760b45 | /CPool_evalexpr_2019/getmin.c | 234a21a336a4ddf3fd756eae55cdb3e5e0c4c9dd | [] | no_license | AlexandreViry/Epitech_2019 | 7b97afc6fbb53ac432592a1b23978921b2823142 | 0926464af8dde9ee472064ae219c0cc0d67d7627 | refs/heads/master | 2023-01-01T13:43:54.392330 | 2020-10-27T15:09:43 | 2020-10-27T15:09:43 | 286,729,566 | 0 | 0 | null | null | null | null | UTF-8 | C | false | false | 304 | c | /*
** EPITECH PROJECT, 2019
** getmin
** File description:
** minimal number
*/
int get_min(char **str,int x)
{
char *str2 = *str;
x = x - 1;
int y = str2[x];
int f = str2[x + 1];
while (y >= 48 && y <= 57 ||y == f) {
x = x - 1;
y = str2[x];
}
return (x);
}
| [
"[email protected]"
] | |
07a05b435a404f444343e2be65d0f84438e48e91 | d59f4db8d99186a314376fcbec871eb35c0fb347 | /Day13/ex02/btree_apply_infix.c | be9f0e4d109423cff8d7e5856738f08dac0cee1b | [] | no_license | ymukmar/Wethinkcode_ | 354bc4d699c73824482909cfe13d416a8bc3a5e9 | 87466fe3627c19d0f63ea766ad10503913de6a88 | refs/heads/master | 2021-01-01T04:19:55.605120 | 2016-04-21T11:37:04 | 2016-04-21T11:37:04 | 56,409,157 | 2 | 0 | null | null | null | null | UTF-8 | C | false | false | 1,104 | c | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* btree_apply_infix.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ymukmar <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2016/04/18 18:16:29 by ymukmar #+# #+# */
/* Updated: 2016/04/18 18:28:16 by ymukmar ### ########.fr */
/* */
/* ************************************************************************** */
#include "ft_btree.h"
void btree_apply_infix(t_btree *root, void (*applyf) (void *))
{
if (root)
{
btree_apply_infix(root->left, applyf);
applyf(root->item);
btree_apply_infix(root->right, applyf);
}
}
| [
"[email protected]"
] | |
7e47fc06a79990c3262910fe4df6c5e96bbd45c7 | be3fcaeb76cb76da8dcd55888071c121edafe6ba | /src/account/imap4.c | a4c646e4e295373053ebefb525ee04a04d930273 | [
"BSD-2-Clause"
] | permissive | DeforaOS/Mailer | d3e3f1957de2ec2f1b0195f34d33196aac1cf6b9 | e63701601144188dd2a2639525521f7fa4357316 | refs/heads/master | 2022-09-19T12:24:33.194657 | 2022-08-08T02:15:06 | 2022-08-08T02:15:06 | 6,466,377 | 2 | 0 | null | null | null | null | UTF-8 | C | false | false | 44,227 | c | /* $Id$ */
/* Copyright (c) 2011-2018 Pierre Pronchery <[email protected]> */
/* This file is part of DeforaOS Desktop Mailer */
/* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
/* FIXME:
* - do not erroneously parse body/header data as potential command completion
* - do not fetch messages when there are none available in the first place
* - openssl should be more explicit when SSL_set_fd() is missing (no BIO)
* - support multiple connections? */
#include <sys/socket.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <limits.h>
#include <ctype.h>
#include <errno.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <openssl/err.h>
#include <openssl/x509.h>
#include <glib.h>
#include <System.h>
#include "Mailer/account.h"
#include "common.c"
/* IMAP4 */
/* private */
/* types */
struct _AccountFolder
{
Folder * folder;
char * name;
AccountMessage ** messages;
size_t messages_cnt;
AccountFolder ** folders;
size_t folders_cnt;
};
struct _AccountMessage
{
Message * message;
unsigned int id;
};
typedef enum _IMAP4CommandStatus
{
I4CS_QUEUED = 0,
I4CS_SENT,
I4CS_ERROR,
I4CS_PARSING,
I4CS_OK
} IMAP4CommandStatus;
typedef enum _IMAP4ConfigValue
{
I4CV_USERNAME = 0,
I4CV_PASSWORD,
I4CV_HOSTNAME,
I4CV_PORT,
I4CV_SSL,
I4CV_PADDING0,
I4CV_PREFIX
} IMAP4Config;
#define I4CV_LAST I4CV_PREFIX
#define I4CV_COUNT (I4CV_LAST + 1)
typedef enum _IMAP4Context
{
I4C_INIT = 0,
I4C_FETCH,
I4C_LIST,
I4C_LOGIN,
I4C_NOOP,
I4C_SELECT,
I4C_STATUS
} IMAP4Context;
typedef enum _IMAP4FetchStatus
{
I4FS_ID = 0,
I4FS_COMMAND,
I4FS_FLAGS,
I4FS_HEADERS,
I4FS_BODY
} IMAP4FetchStatus;
typedef struct _IMAP4Command
{
uint16_t id;
IMAP4CommandStatus status;
IMAP4Context context;
char * buf;
size_t buf_cnt;
union
{
struct
{
AccountFolder * folder;
AccountMessage * message;
unsigned int id;
IMAP4FetchStatus status;
unsigned int size;
} fetch;
struct
{
AccountFolder * parent;
} list;
struct
{
AccountFolder * folder;
AccountMessage * message;
} select;
struct
{
AccountFolder * folder;
} status;
} data;
} IMAP4Command;
typedef struct _AccountPlugin
{
AccountPluginHelper * helper;
AccountConfig * config;
struct addrinfo * ai;
struct addrinfo * aip;
int fd;
SSL * ssl;
guint source;
GIOChannel * channel;
char * rd_buf;
size_t rd_buf_cnt;
guint rd_source;
guint wr_source;
IMAP4Command * queue;
size_t queue_cnt;
uint16_t queue_id;
AccountFolder folders;
} IMAP4;
/* variables */
static char const _imap4_type[] = "IMAP4";
static char const _imap4_name[] = "IMAP4 server";
AccountConfig const _imap4_config[I4CV_COUNT + 1] =
{
{ "username", "Username", ACT_STRING, NULL },
{ "password", "Password", ACT_PASSWORD, NULL },
{ "hostname", "Server hostname", ACT_STRING, NULL },
{ "port", "Server port", ACT_UINT16, 143 },
{ "ssl", "Use SSL", ACT_BOOLEAN, 0 },
#if 0 /* XXX not implemented yet */
{ "sent", "Sent mails folder", ACT_NONE, NULL },
{ "draft", "Draft mails folder", ACT_NONE, NULL },
#endif
{ NULL, NULL, ACT_SEPARATOR, NULL },
{ "prefix", "Prefix", ACT_STRING, NULL },
{ NULL, NULL, ACT_NONE, NULL }
};
/* prototypes */
/* plug-in */
static IMAP4 * _imap4_init(AccountPluginHelper * helper);
static int _imap4_destroy(IMAP4 * imap4);
static AccountConfig * _imap4_get_config(IMAP4 * imap4);
static int _imap4_start(IMAP4 * imap4);
static void _imap4_stop(IMAP4 * imap4);
static int _imap4_refresh(IMAP4 * imap4, AccountFolder * folder,
AccountMessage * message);
/* useful */
static IMAP4Command * _imap4_command(IMAP4 * imap4, IMAP4Context context,
char const * command);
static int _imap4_parse(IMAP4 * imap4);
/* events */
static void _imap4_event(IMAP4 * imap4, AccountEventType type);
static void _imap4_event_status(IMAP4 * imap4, AccountStatus status,
char const * message);
/* folders */
static AccountFolder * _imap4_folder_new(IMAP4 * imap4, AccountFolder * parent,
char const * name);
static void _imap4_folder_delete(IMAP4 * imap4,
AccountFolder * folder);
static AccountFolder * _imap4_folder_get_folder(IMAP4 * imap4,
AccountFolder * folder, char const * name);
static AccountMessage * _imap4_folder_get_message(IMAP4 * imap4,
AccountFolder * folder, unsigned int id);
/* messages */
static AccountMessage * _imap4_message_new(IMAP4 * imap4,
AccountFolder * folder, unsigned int id);
static void _imap4_message_delete(IMAP4 * imap4,
AccountMessage * message);
/* callbacks */
static gboolean _on_connect(gpointer data);
static gboolean _on_noop(gpointer data);
static gboolean _on_watch_can_connect(GIOChannel * source,
GIOCondition condition, gpointer data);
static gboolean _on_watch_can_handshake(GIOChannel * source,
GIOCondition condition, gpointer data);
static gboolean _on_watch_can_read(GIOChannel * source, GIOCondition condition,
gpointer data);
static gboolean _on_watch_can_read_ssl(GIOChannel * source,
GIOCondition condition, gpointer data);
static gboolean _on_watch_can_write(GIOChannel * source, GIOCondition condition,
gpointer data);
static gboolean _on_watch_can_write_ssl(GIOChannel * source,
GIOCondition condition, gpointer data);
/* public */
/* variables */
AccountPluginDefinition account_plugin =
{
_imap4_type,
_imap4_name,
NULL,
NULL,
_imap4_config,
_imap4_init,
_imap4_destroy,
_imap4_get_config,
NULL,
_imap4_start,
_imap4_stop,
_imap4_refresh
};
/* protected */
/* functions */
/* plug-in */
/* imap4_init */
static IMAP4 * _imap4_init(AccountPluginHelper * helper)
{
IMAP4 * imap4;
if((imap4 = malloc(sizeof(*imap4))) == NULL)
return NULL;
memset(imap4, 0, sizeof(*imap4));
imap4->helper = helper;
if((imap4->config = malloc(sizeof(_imap4_config))) == NULL)
{
free(imap4);
return NULL;
}
memcpy(imap4->config, &_imap4_config, sizeof(_imap4_config));
imap4->ai = NULL;
imap4->aip = NULL;
imap4->fd = -1;
return imap4;
}
/* imap4_destroy */
static int _imap4_destroy(IMAP4 * imap4)
{
size_t i;
#ifdef DEBUG
fprintf(stderr, "DEBUG: %s()\n", __func__);
#endif
if(imap4 == NULL) /* XXX _imap4_destroy() may be called uninitialized */
return 0;
_imap4_stop(imap4);
#if 1 /* XXX anything wrong here? */
_imap4_folder_delete(imap4, &imap4->folders);
#endif
for(i = 0; i < sizeof(_imap4_config) / sizeof(*_imap4_config); i++)
if(_imap4_config[i].type == ACT_STRING
|| _imap4_config[i].type == ACT_PASSWORD)
free(imap4->config[i].value);
free(imap4->config);
free(imap4);
return 0;
}
/* imap4_get_config */
static AccountConfig * _imap4_get_config(IMAP4 * imap4)
{
return imap4->config;
}
/* imap4_start */
static int _imap4_start(IMAP4 * imap4)
{
_imap4_event(imap4, AET_STARTED);
if(imap4->fd >= 0 || imap4->source != 0)
/* already started */
return 0;
imap4->source = g_idle_add(_on_connect, imap4);
return 0;
}
/* imap4_stop */
static void _imap4_stop(IMAP4 * imap4)
{
size_t i;
if(imap4->ssl != NULL)
SSL_free(imap4->ssl);
imap4->ssl = NULL;
if(imap4->rd_source != 0)
g_source_remove(imap4->rd_source);
imap4->rd_source = 0;
if(imap4->wr_source != 0)
g_source_remove(imap4->wr_source);
imap4->wr_source = 0;
if(imap4->source != 0)
g_source_remove(imap4->source);
imap4->source = 0;
if(imap4->channel != NULL)
{
g_io_channel_shutdown(imap4->channel, TRUE, NULL);
g_io_channel_unref(imap4->channel);
imap4->fd = -1;
}
imap4->channel = NULL;
for(i = 0; i < imap4->queue_cnt; i++)
free(imap4->queue[i].buf);
free(imap4->queue);
imap4->queue = NULL;
imap4->queue_cnt = 0;
if(imap4->fd >= 0)
close(imap4->fd);
imap4->fd = -1;
imap4->aip = NULL;
if(imap4->ai != NULL)
freeaddrinfo(imap4->ai);
imap4->ai = NULL;
_imap4_event(imap4, AET_STOPPED);
}
/* imap4_refresh */
static int _imap4_refresh(IMAP4 * imap4, AccountFolder * folder,
AccountMessage * message)
{
IMAP4Command * cmd;
int len;
char * buf;
#ifdef DEBUG
fprintf(stderr, "DEBUG: %s() %u\n", __func__, (message != NULL)
? message->id : 0);
#endif
if((len = snprintf(NULL, 0, "EXAMINE \"%s\"", folder->name)) < 0
|| (buf = malloc(++len)) == NULL)
return -1;
snprintf(buf, len, "EXAMINE \"%s\"", folder->name);
cmd = _imap4_command(imap4, I4C_SELECT, buf);
free(buf);
if(cmd == NULL)
return -1;
cmd->data.select.folder = folder;
cmd->data.select.message = message;
return 0;
}
/* private */
/* functions */
/* useful */
/* imap4_command */
static IMAP4Command * _imap4_command(IMAP4 * imap4, IMAP4Context context,
char const * command)
{
IMAP4Command * p;
size_t len;
#ifdef DEBUG
fprintf(stderr, "DEBUG: %s(\"%s\", %p)\n", __func__, command,
(void *)imap4->channel);
#endif
/* abort if the command is invalid */
if(command == NULL || (len = strlen(command)) == 0)
return NULL;
/* abort if there is no active connection */
if(imap4->channel == NULL)
return NULL;
/* queue the command */
len += 9;
if((p = realloc(imap4->queue, sizeof(*p) * (imap4->queue_cnt + 1)))
== NULL)
return NULL;
imap4->queue = p;
p = &imap4->queue[imap4->queue_cnt];
p->id = imap4->queue_id++;
p->context = context;
p->status = I4CS_QUEUED;
if((p->buf = malloc(len)) == NULL)
return NULL;
p->buf_cnt = snprintf(p->buf, len, "a%04x %s\r\n", p->id, command);
memset(&p->data, 0, sizeof(p->data));
if(imap4->queue_cnt++ == 0)
{
if(imap4->source != 0)
{
/* cancel the pending NOOP operation */
g_source_remove(imap4->source);
imap4->source = 0;
}
imap4->wr_source = g_io_add_watch(imap4->channel, G_IO_OUT,
(imap4->ssl != NULL) ? _on_watch_can_write_ssl
: _on_watch_can_write, imap4);
}
return p;
}
/* imap4_parse */
static int _parse_context(IMAP4 * imap4, char const * answer);
static int _context_fetch(IMAP4 * imap4, char const * answer);
static int _context_fetch_body(IMAP4 * imap4, char const * answer);
static int _context_fetch_command(IMAP4 * imap4, char const * answer);
static int _context_fetch_flags(IMAP4 * imap4, char const * answer);
static int _context_fetch_headers(IMAP4 * imap4, char const * answer);
static int _context_fetch_id(IMAP4 * imap4, char const * answer);
static int _context_init(IMAP4 * imap4);
static int _context_list(IMAP4 * imap4, char const * answer);
static int _context_login(IMAP4 * imap4, char const * answer);
static int _context_select(IMAP4 * imap4);
static int _context_status(IMAP4 * imap4, char const * answer);
static int _imap4_parse(IMAP4 * imap4)
{
AccountPluginHelper * helper = imap4->helper;
size_t i;
size_t j;
IMAP4Command * cmd;
char buf[8];
#ifdef DEBUG
fprintf(stderr, "DEBUG: %s()\n", __func__);
#endif
for(i = 0, j = 0;; j = ++i)
{
/* look for carriage return sequences */
for(; i < imap4->rd_buf_cnt; i++)
if(imap4->rd_buf[i] == '\r' && i + 1 < imap4->rd_buf_cnt
&& imap4->rd_buf[++i] == '\n')
break;
/* if no carriage return was found wait for more input */
if(i == imap4->rd_buf_cnt)
break;
/* if no command was sent read more lines */
if(imap4->queue_cnt == 0)
continue;
imap4->rd_buf[i - 1] = '\0';
cmd = &imap4->queue[0];
/* if we have just sent a command match the answer */
if(cmd->status == I4CS_SENT)
{
snprintf(buf, sizeof(buf), "a%04x ", cmd->id);
#ifdef DEBUG
fprintf(stderr, "DEBUG: %s() expecting \"%s\"\n",
__func__, buf);
#endif
if(strncmp(&imap4->rd_buf[j], "* ", 2) == 0)
j += 2;
else if(strncmp(&imap4->rd_buf[j], buf, 6) == 0)
{
j += 6;
cmd->status = I4CS_PARSING;
if(strncmp("BAD ", &imap4->rd_buf[j], 4) == 0)
/* FIXME report and pop queue instead */
helper->error(NULL,
&imap4->rd_buf[j + 4],
1);
}
}
if(_parse_context(imap4, &imap4->rd_buf[j]) != 0)
cmd->status = I4CS_ERROR;
}
if(j != 0)
{
imap4->rd_buf_cnt -= j;
memmove(imap4->rd_buf, &imap4->rd_buf[j], imap4->rd_buf_cnt);
}
return 0;
}
static int _parse_context(IMAP4 * imap4, char const * answer)
{
int ret = -1;
IMAP4Command * cmd = &imap4->queue[0];
#ifdef DEBUG
fprintf(stderr, "DEBUG: %s(\"%s\") %u, %u\n", __func__, answer,
cmd->context, cmd->status);
#endif
switch(cmd->context)
{
case I4C_FETCH:
return _context_fetch(imap4, answer);
case I4C_INIT:
return _context_init(imap4);
case I4C_LIST:
return _context_list(imap4, answer);
case I4C_LOGIN:
return _context_login(imap4, answer);
case I4C_NOOP:
if(cmd->status != I4CS_PARSING)
return 0;
cmd->status = I4CS_OK;
return 0;
case I4C_SELECT:
return _context_select(imap4);
case I4C_STATUS:
return _context_status(imap4, answer);
}
return ret;
}
static int _context_fetch(IMAP4 * imap4, char const * answer)
{
IMAP4Command * cmd = &imap4->queue[0];
#ifdef DEBUG
fprintf(stderr, "DEBUG: %s(\"%s\")\n", __func__, answer);
#endif
if(cmd->status == I4CS_PARSING)
{
cmd->status = I4CS_OK;
return 0;
}
switch(cmd->data.fetch.status)
{
case I4FS_ID:
return _context_fetch_id(imap4, answer);
case I4FS_COMMAND:
return _context_fetch_command(imap4, answer);
case I4FS_FLAGS:
return _context_fetch_flags(imap4, answer);
case I4FS_BODY:
return _context_fetch_body(imap4, answer);
case I4FS_HEADERS:
return _context_fetch_headers(imap4, answer);
}
return -1;
}
static int _context_fetch_body(IMAP4 * imap4, char const * answer)
{
AccountPluginHelper * helper = imap4->helper;
IMAP4Command * cmd = &imap4->queue[0];
AccountMessage * message = cmd->data.fetch.message;
size_t i;
/* check the size */
if(cmd->data.fetch.size == 0)
{
/* XXX may not be the case (flags...) */
if(strcmp(answer, ")") == 0)
{
cmd->data.fetch.status = I4FS_ID;
return 0;
}
else
{
cmd->data.fetch.status = I4FS_COMMAND;
return _context_fetch(imap4, answer);
}
}
if((i = strlen(answer) + 2) <= cmd->data.fetch.size)
cmd->data.fetch.size -= i;
helper->message_set_body(message->message, answer, strlen(answer), 1);
helper->message_set_body(message->message, "\r\n", 2, 1);
return 0;
}
static int _context_fetch_command(IMAP4 * imap4, char const * answer)
{
IMAP4Command * cmd = &imap4->queue[0];
AccountFolder * folder = cmd->data.fetch.folder;
AccountMessage * message = cmd->data.fetch.message;
unsigned int id = cmd->data.fetch.id;
char * p;
size_t i;
/* skip spaces */
for(i = 0; answer[i] == ' '; i++);
if(strncmp(&answer[i], "FLAGS ", 6) == 0)
{
cmd->data.fetch.status = I4FS_FLAGS;
return _context_fetch(imap4, answer);
}
/* XXX assumes this is going to be a message content */
/* skip the command's name */
for(; answer[i] != '\0' && answer[i] != ' '; i++);
/* skip spaces */
for(; answer[i] == ' '; i++);
/* obtain the size */
if(answer[i] != '{')
return -1;
cmd->data.fetch.size = strtoul(&answer[++i], &p, 10);
if(answer[i] == '\0' || *p != '}' || cmd->data.fetch.size == 0)
return -1;
if((message = _imap4_folder_get_message(imap4, folder, id)) != NULL)
{
cmd->data.fetch.status = I4FS_HEADERS;
cmd->data.fetch.message = message;
}
return (message != NULL) ? 0 : -1;
}
static int _context_fetch_flags(IMAP4 * imap4, char const * answer)
{
AccountPluginHelper * helper = imap4->helper;
IMAP4Command * cmd = &imap4->queue[0];
AccountMessage * message = cmd->data.fetch.message;
size_t i;
size_t j;
size_t k;
struct
{
char const * name;
MailerMessageFlag flag;
} flags[] = {
{ "\\Answered", MMF_ANSWERED },
{ "\\Draft", MMF_DRAFT }
};
/* skip spaces */
for(i = 0; answer[i] == ' '; i++);
if(strncmp(&answer[i], "FLAGS ", 6) != 0)
{
cmd->data.fetch.status = I4FS_ID;
return -1;
}
/* skip spaces */
for(i += 6; answer[i] == ' '; i++);
if(answer[i] != '(')
return -1;
for(i++; answer[i] != '\0' && answer[i] != ')';)
{
for(j = i; isalpha((unsigned char)answer[j])
|| answer[j] == '\\' || answer[j] == '$'; j++);
/* give up if there is no flag */
if(j == i)
{
for(; answer[i] != '\0' && answer[i] != ')'; i++);
break;
}
/* apply the flag */
for(k = 0; k < sizeof(flags) / sizeof(*flags); k++)
if(strncmp(&answer[i], flags[k].name, j - i) == 0)
{
/* FIXME make sure message != NULL */
if(message == NULL)
continue;
helper->message_set_flag(message->message,
flags[k].flag);
}
/* skip spaces */
for(i = j; answer[i] == ' '; i++);
}
if(answer[i] != ')')
return -1;
/* skip spaces */
for(i++; answer[i] == ' '; i++);
if(answer[i] == ')')
{
/* the current command seems to be completed */
cmd->data.fetch.status = I4FS_ID;
return 0;
}
cmd->data.fetch.status = I4FS_COMMAND;
return _context_fetch(imap4, &answer[i]);
}
static int _context_fetch_headers(IMAP4 * imap4, char const * answer)
{
AccountPluginHelper * helper = imap4->helper;
IMAP4Command * cmd = &imap4->queue[0];
AccountMessage * message = cmd->data.fetch.message;
size_t i;
/* check the size */
if((i = strlen(answer) + 2) <= cmd->data.fetch.size)
cmd->data.fetch.size -= i;
if(strcmp(answer, "") == 0)
{
/* beginning of the body */
cmd->data.fetch.status = I4FS_BODY;
helper->message_set_body(message->message, NULL, 0, 0);
}
/* XXX check this before parsing anything */
else if(cmd->data.fetch.size == 0 || i > cmd->data.fetch.size)
return 0;
else
helper->message_set_header(message->message, answer);
return 0;
}
static int _context_fetch_id(IMAP4 * imap4, char const * answer)
{
IMAP4Command * cmd = &imap4->queue[0];
unsigned int id = cmd->data.fetch.id;
char * p;
size_t i;
id = strtol(answer, &p, 10);
if(answer[0] == '\0' || *p != ' ')
return 0;
cmd->data.fetch.id = id;
#ifdef DEBUG
fprintf(stderr, "DEBUG: %s() id=%u\n", __func__, id);
#endif
answer = p;
if(strncmp(answer, " FETCH ", 7) != 0)
return -1;
/* skip spaces */
for(i = 7; answer[i] == ' '; i++);
if(answer[i++] != '(')
return 0;
/* fallback */
answer = &answer[i];
cmd->data.fetch.status = I4FS_COMMAND;
return _context_fetch_command(imap4, answer);
}
static int _context_init(IMAP4 * imap4)
{
IMAP4Command * cmd = &imap4->queue[0];
char const * p;
char const * q;
gchar * r;
cmd->status = I4CS_OK;
if((p = imap4->config[I4CV_USERNAME].value) == NULL || *p == '\0')
return -1;
if((q = imap4->config[I4CV_PASSWORD].value) == NULL || *q == '\0')
return -1;
r = g_strdup_printf("%s %s %s", "LOGIN", p, q);
cmd = _imap4_command(imap4, I4C_LOGIN, r);
g_free(r);
return (cmd != NULL) ? 0 : -1;
}
static int _context_list(IMAP4 * imap4, char const * answer)
{
IMAP4Command * cmd = &imap4->queue[0];
AccountFolder * folder;
AccountFolder * parent = cmd->data.list.parent;
char const * p = answer;
gchar * q;
char const haschildren[] = "\\HasChildren";
int recurse = 0;
char reference = '\0';
char buf[64];
#ifdef DEBUG
fprintf(stderr, "DEBUG: %s(\"%s\")\n", __func__, answer);
#endif
if(strncmp("OK", p, 2) == 0)
{
cmd->status = I4CS_OK;
return 0;
}
if(strncmp("LIST ", p, 5) != 0)
return -1;
p += 5;
if(*p == '(') /* parse flags */
{
for(p++; *p == '\\';)
{
#ifdef DEBUG
fprintf(stderr, "DEBUG: %s() flag \"%s\"\n", __func__,
p);
#endif
if(strncmp(p, haschildren, sizeof(haschildren) - 1)
== 0)
{
p += sizeof(haschildren) - 1;
recurse = 1;
}
else
/* skip until end of flag */
for(p++; isalnum((unsigned char)*p); p++);
/* skip spaces */
for(; *p == ' '; p++);
if(*p == ')')
break;
}
if(*p != ')')
return -1;
p++;
}
if(*p == ' ') /* skip spaces */
for(p++; *p != '\0' && *p == ' '; p++);
if(*p == '\"') /* skip reference */
{
if(p[1] != '\0' && p[1] != '"' && p[2] == '"')
reference = p[1];
for(p++; *p != '\0' && *p++ != '\"';);
}
if(*p == ' ') /* skip spaces */
for(p++; *p != '\0' && *p == ' '; p++);
/* read the folder name */
buf[0] = '\0';
if(*p == '\"')
sscanf(++p, "%63[^\"]", buf);
else
sscanf(p, "%63s", buf);
buf[63] = '\0';
if(buf[0] != '\0' && (folder = _imap4_folder_get_folder(imap4, parent,
buf)) != NULL
/* FIXME escape the mailbox' name instead */
&& strchr(buf, '"') == NULL)
{
q = g_strdup_printf("%s \"%s\" (%s)", "STATUS", buf,
"MESSAGES RECENT UNSEEN");
if((cmd = _imap4_command(imap4, I4C_STATUS, q)) != NULL)
cmd->data.status.folder = folder;
g_free(q);
if(cmd != NULL && recurse == 1 && reference != '\0')
{
q = g_strdup_printf("%s \"\" \"%s%c%%\"", "LIST", buf,
reference);
if((cmd = _imap4_command(imap4, I4C_LIST, q)) != NULL)
cmd->data.list.parent = folder;
g_free(q);
}
}
return (cmd != NULL) ? 0 : -1;
}
static int _context_login(IMAP4 * imap4, char const * answer)
{
AccountPluginHelper * helper = imap4->helper;
IMAP4Command * cmd = &imap4->queue[0];
char const * prefix = imap4->config[I4CV_PREFIX].value;
gchar * q;
if(cmd->status != I4CS_PARSING)
return 0;
if(strncmp("OK", answer, 2) != 0)
return -helper->error(helper->account, "Authentication failed",
1);
cmd->status = I4CS_OK;
if((q = g_strdup_printf("%s \"\" \"%s%%\"", "LIST", (prefix != NULL)
? prefix : "")) == NULL)
return -1;
cmd = _imap4_command(imap4, I4C_LIST, q);
g_free(q);
if(cmd == NULL)
return -1;
cmd->data.list.parent = &imap4->folders;
return 0;
}
static int _context_select(IMAP4 * imap4)
{
IMAP4Command * cmd = &imap4->queue[0];
AccountFolder * folder;
AccountMessage * message;
char buf[64];
if(cmd->status != I4CS_PARSING)
return 0;
cmd->status = I4CS_OK;
if((folder = cmd->data.select.folder) == NULL)
return 0; /* XXX really is an error */
if((message = cmd->data.select.message) == NULL)
/* FIXME queue commands in batches instead */
snprintf(buf, sizeof(buf), "%s %s %s", "FETCH", "1:*",
"(FLAGS BODY.PEEK[HEADER])");
else
snprintf(buf, sizeof(buf), "%s %u %s", "FETCH", message->id,
"BODY.PEEK[]");
if((cmd = _imap4_command(imap4, I4C_FETCH, buf)) == NULL)
return -1;
cmd->data.fetch.folder = folder;
cmd->data.fetch.message = message;
cmd->data.fetch.id = (message != NULL) ? message->id : 0;
cmd->data.fetch.status = I4FS_ID;
cmd->data.fetch.size = 0;
return 0;
}
static int _context_status(IMAP4 * imap4, char const * answer)
{
IMAP4Command * cmd = &imap4->queue[0];
char const * p;
char const messages[] = "MESSAGES";
char const recent[] = "RECENT";
char const unseen[] = "UNSEEN";
unsigned int u;
#ifdef DEBUG
fprintf(stderr, "DEBUG: %s(\"%s\")\n", __func__, answer);
#endif
p = answer;
if(strncmp("OK", p, 2) == 0)
{
cmd->status = I4CS_OK;
return 0;
}
else if(strncmp("NO", p, 2) == 0)
{
cmd->status = I4CS_ERROR;
return 0;
}
if(strncmp("STATUS ", p, 7) != 0)
return 0;
p += 7;
if(*p == '\"') /* skip reference */
for(p++; *p != '\0' && *p++ != '\"';);
if(*p == ' ') /* skip spaces */
for(p++; *p != '\0' && *p == ' '; p++);
if(*p == '(')
/* parse the data items */
for(p++; *p != '\0' && *p != ')'; p++)
{
if(strncmp(p, messages, sizeof(messages) - 1) == 0
&& p[sizeof(messages) - 1] == ' ')
{
/* number of messages in the mailbox */
p += sizeof(messages);
sscanf(p, "%u", &u);
/* FIXME really implement */
#ifdef DEBUG
fprintf(stderr, "DEBUG: %s() %u messages\n",
__func__, u);
#endif
}
else if(strncmp(p, recent, sizeof(recent) - 1) == 0
&& p[sizeof(recent) - 1] == ' ')
{
/* number of recent messages in the mailbox */
p += sizeof(recent);
sscanf(p, "%u", &u);
/* FIXME really implement */
#ifdef DEBUG
fprintf(stderr, "DEBUG: %s() %u recent\n",
__func__, u);
#endif
}
else if(strncmp(p, unseen, sizeof(unseen) - 1) == 0
&& p[sizeof(unseen) - 1] == ' ')
{
/* number of unseen messages in the mailbox */
p += sizeof(unseen);
sscanf(p, "%u", &u);
/* FIXME really implement */
#ifdef DEBUG
fprintf(stderr, "DEBUG: %s() %u unseen\n",
__func__, u);
#endif
}
else
/* skip until the next space */
for(; *p != '\0' && *p != ' ' && *p != ')';
p++);
/* skip until the next space */
for(; *p != '\0' && *p != ' ' && *p != ')'; p++);
}
return 0;
}
/* imap4_event */
static void _imap4_event(IMAP4 * imap4, AccountEventType type)
{
AccountPluginHelper * helper = imap4->helper;
AccountEvent event;
memset(&event, 0, sizeof(event));
switch((event.status.type = type))
{
case AET_STARTED:
case AET_STOPPED:
break;
default:
/* XXX not handled */
return;
}
helper->event(helper->account, &event);
}
/* imap4_event_status */
static void _imap4_event_status(IMAP4 * imap4, AccountStatus status,
char const * message)
{
AccountPluginHelper * helper = imap4->helper;
AccountEvent event;
memset(&event, 0, sizeof(event));
event.status.type = AET_STATUS;
event.status.status = status;
event.status.message = message;
helper->event(helper->account, &event);
}
/* imap4_folder_new */
static AccountFolder * _imap4_folder_new(IMAP4 * imap4, AccountFolder * parent,
char const * name)
{
AccountPluginHelper * helper = imap4->helper;
AccountFolder * folder;
AccountFolder ** p;
FolderType type = FT_FOLDER;
struct
{
char const * name;
FolderType type;
} name_type[] =
{
{ "Inbox", FT_INBOX },
{ "Drafts", FT_DRAFTS },
{ "Trash", FT_TRASH },
{ "Sent", FT_SENT }
};
size_t i;
size_t len;
if((p = realloc(parent->folders, sizeof(*p) * (parent->folders_cnt
+ 1))) == NULL)
return NULL;
parent->folders = p;
if((folder = object_new(sizeof(*folder))) == NULL)
return NULL;
folder->name = strdup(name);
if(parent == &imap4->folders)
for(i = 0; i < sizeof(name_type) / sizeof(*name_type); i++)
if(strcasecmp(name_type[i].name, name) == 0)
{
type = name_type[i].type;
name = name_type[i].name;
break;
}
/* shorten the name as required if has a parent */
if(parent->name != NULL && (len = strlen(parent->name)) > 0
&& strncmp(name, parent->name, len) == 0)
name = &name[len + 1];
folder->folder = helper->folder_new(helper->account, folder,
parent->folder, type, name);
folder->messages = NULL;
folder->messages_cnt = 0;
folder->folders = NULL;
folder->folders_cnt = 0;
if(folder->folder == NULL || folder->name == NULL)
{
_imap4_folder_delete(imap4, folder);
return NULL;
}
parent->folders[parent->folders_cnt++] = folder;
return folder;
}
/* imap4_folder_delete */
static void _imap4_folder_delete(IMAP4 * imap4, AccountFolder * folder)
{
size_t i;
if(folder->folder != NULL)
imap4->helper->folder_delete(folder->folder);
free(folder->name);
for(i = 0; i < folder->messages_cnt; i++)
_imap4_message_delete(imap4, folder->messages[i]);
free(folder->messages);
for(i = 0; i < folder->folders_cnt; i++)
_imap4_folder_delete(imap4, folder->folders[i]);
free(folder->folders);
/* XXX rather ugly */
if(folder != &imap4->folders)
object_delete(folder);
}
/* imap4_folder_get_folder */
static AccountFolder * _imap4_folder_get_folder(IMAP4 * imap4,
AccountFolder * folder, char const * name)
{
size_t i;
#ifdef DEBUG
fprintf(stderr, "DEBUG: %s(\"%s\", \"%s\")\n", __func__, folder->name,
name);
#endif
for(i = 0; i < folder->folders_cnt; i++)
if(strcmp(folder->folders[i]->name, name) == 0)
return folder->folders[i];
return _imap4_folder_new(imap4, folder, name);
}
/* imap4_folder_get_message */
static AccountMessage * _imap4_folder_get_message(IMAP4 * imap4,
AccountFolder * folder, unsigned int id)
{
size_t i;
#ifdef DEBUG
fprintf(stderr, "DEBUG: %s(\"%s\", %u)\n", __func__, folder->name, id);
#endif
for(i = 0; i < folder->messages_cnt; i++)
if(folder->messages[i]->id == id)
return folder->messages[i];
return _imap4_message_new(imap4, folder, id);
}
/* imap4_message_new */
static AccountMessage * _imap4_message_new(IMAP4 * imap4,
AccountFolder * folder, unsigned int id)
{
AccountPluginHelper * helper = imap4->helper;
AccountMessage * message;
AccountMessage ** p;
if((p = realloc(folder->messages, sizeof(*p)
* (folder->messages_cnt + 1))) == NULL)
return NULL;
folder->messages = p;
if((message = object_new(sizeof(*message))) == NULL)
return NULL;
message->id = id;
if((message->message = helper->message_new(helper->account,
folder->folder, message)) == NULL)
{
_imap4_message_delete(imap4, message);
return NULL;
}
folder->messages[folder->messages_cnt++] = message;
return message;
}
/* imap4_message_delete */
static void _imap4_message_delete(IMAP4 * imap4,
AccountMessage * message)
{
if(message->message != NULL)
imap4->helper->message_delete(message->message);
object_delete(message);
}
/* callbacks */
/* on_idle */
static int _connect_address(IMAP4 * imap4, char const * hostname,
struct addrinfo * ai);
static int _connect_channel(IMAP4 * imap4);
static gboolean _on_connect(gpointer data)
{
IMAP4 * imap4 = data;
AccountPluginHelper * helper = imap4->helper;
char const * hostname;
char const * p;
uint16_t port;
#ifdef DEBUG
fprintf(stderr, "DEBUG: %s()\n", __func__);
#endif
imap4->source = 0;
/* get the hostname and port */
if((hostname = imap4->config[I4CV_HOSTNAME].value) == NULL)
{
helper->error(helper->account, "No hostname set", 1);
return FALSE;
}
if((p = imap4->config[I4CV_PORT].value) == NULL)
return FALSE;
port = (unsigned long)p;
/* lookup the address */
if(_common_lookup(hostname, port, &imap4->ai) != 0)
{
helper->error(helper->account, error_get(NULL), 1);
return FALSE;
}
for(imap4->aip = imap4->ai; imap4->aip != NULL;
imap4->aip = imap4->aip->ai_next)
if(_connect_address(imap4, hostname, imap4->aip) == 0)
break;
if(imap4->aip == NULL)
_imap4_stop(imap4);
return FALSE;
}
static int _connect_address(IMAP4 * imap4, char const * hostname,
struct addrinfo * ai)
{
AccountPluginHelper * helper = imap4->helper;
int res;
char * q;
char buf[128];
/* create the socket */
if((imap4->fd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol))
== -1)
return -helper->error(helper->account, strerror(errno), 1);
if((res = fcntl(imap4->fd, F_GETFL)) >= 0
&& fcntl(imap4->fd, F_SETFL, res | O_NONBLOCK) == -1)
/* ignore this error */
/* FIXME report properly as a warning instead */
helper->error(NULL, strerror(errno), 1);
/* report the current status */
if((q = _common_lookup_print(ai)) != NULL)
snprintf(buf, sizeof(buf), "Connecting to %s (%s)", hostname,
q);
else
snprintf(buf, sizeof(buf), "Connecting to %s", hostname);
free(q);
_imap4_event_status(imap4, AS_CONNECTING, buf);
/* connect to the remote host */
if((connect(imap4->fd, ai->ai_addr, ai->ai_addrlen) != 0
&& errno != EINPROGRESS && errno != EINTR)
|| _connect_channel(imap4) != 0)
{
snprintf(buf, sizeof(buf), "%s (%s)", "Connection failed",
strerror(errno));
return -helper->error(helper->account, buf, 1);
}
imap4->wr_source = g_io_add_watch(imap4->channel, G_IO_OUT,
_on_watch_can_connect, imap4);
return 0;
}
static int _connect_channel(IMAP4 * imap4)
{
AccountPluginHelper * helper = imap4->helper;
GError * error = NULL;
#ifdef DEBUG
fprintf(stderr, "DEBUG: %s()\n", __func__);
#endif
/* prepare queue */
if((imap4->queue = malloc(sizeof(*imap4->queue))) == NULL)
return -helper->error(helper->account, strerror(errno), 1);
imap4->queue[0].id = 0;
imap4->queue[0].context = I4C_INIT;
imap4->queue[0].status = I4CS_SENT;
imap4->queue[0].buf = NULL;
imap4->queue[0].buf_cnt = 0;
imap4->queue_cnt = 1;
imap4->queue_id = 1;
/* setup channel */
imap4->channel = g_io_channel_unix_new(imap4->fd);
g_io_channel_set_encoding(imap4->channel, NULL, &error);
g_io_channel_set_buffered(imap4->channel, FALSE);
return 0;
}
/* on_noop */
static gboolean _on_noop(gpointer data)
{
IMAP4 * imap4 = data;
_imap4_command(imap4, I4C_NOOP, "NOOP");
imap4->source = 0;
return FALSE;
}
/* on_watch_can_connect */
static gboolean _on_watch_can_connect(GIOChannel * source,
GIOCondition condition, gpointer data)
{
IMAP4 * imap4 = data;
AccountPluginHelper * helper = imap4->helper;
int res;
socklen_t s = sizeof(res);
char const * hostname = imap4->config[I4CV_HOSTNAME].value;
SSL_CTX * ssl_ctx;
char buf[128];
char * q;
if(condition != G_IO_OUT || source != imap4->channel)
return FALSE; /* should not happen */
#ifdef DEBUG
fprintf(stderr, "DEBUG: %s() connected\n", __func__);
#endif
if(getsockopt(imap4->fd, SOL_SOCKET, SO_ERROR, &res, &s) != 0
|| res != 0)
{
snprintf(buf, sizeof(buf), "%s (%s)", "Connection failed",
strerror(res));
helper->error(helper->account, buf, 1);
/* FIXME try the next address instead */
_imap4_stop(imap4);
return FALSE;
}
if(imap4->aip != NULL && (q = _common_lookup_print(imap4->aip)) != NULL)
{
snprintf(buf, sizeof(buf), "Connected to %s (%s)", hostname,
q);
free(q);
}
else
snprintf(buf, sizeof(buf), "Connected to %s", hostname);
_imap4_event_status(imap4, AS_CONNECTED, buf);
imap4->wr_source = 0;
/* setup SSL */
if(imap4->config[I4CV_SSL].value != NULL)
{
if((ssl_ctx = helper->get_ssl_context(helper->account)) == NULL)
/* FIXME report error */
return FALSE;
if((imap4->ssl = SSL_new(ssl_ctx)) == NULL)
{
helper->error(helper->account, ERR_error_string(
ERR_get_error(), buf), 1);
return FALSE;
}
if(SSL_set_fd(imap4->ssl, imap4->fd) != 1)
{
ERR_error_string(ERR_get_error(), buf);
SSL_free(imap4->ssl);
imap4->ssl = NULL;
helper->error(helper->account, buf, 1);
return FALSE;
}
SSL_set_connect_state(imap4->ssl);
/* perform initial handshake */
imap4->wr_source = g_io_add_watch(imap4->channel, G_IO_OUT,
_on_watch_can_handshake, imap4);
return FALSE;
}
/* wait for the server's banner */
imap4->rd_source = g_io_add_watch(imap4->channel, G_IO_IN,
_on_watch_can_read, imap4);
return FALSE;
}
/* on_watch_can_handshake */
static int _handshake_verify(IMAP4 * imap4);
static gboolean _on_watch_can_handshake(GIOChannel * source,
GIOCondition condition, gpointer data)
{
IMAP4 * imap4 = data;
AccountPluginHelper * helper = imap4->helper;
int res;
int err;
char buf[128];
if((condition != G_IO_IN && condition != G_IO_OUT)
|| source != imap4->channel || imap4->ssl == NULL)
return FALSE; /* should not happen */
#ifdef DEBUG
fprintf(stderr, "DEBUG: %s()\n", __func__);
#endif
imap4->wr_source = 0;
imap4->rd_source = 0;
if((res = SSL_do_handshake(imap4->ssl)) == 1)
{
if(_handshake_verify(imap4) != 0)
{
_imap4_stop(imap4);
return FALSE;
}
/* wait for the server's banner */
imap4->rd_source = g_io_add_watch(imap4->channel, G_IO_IN,
_on_watch_can_read_ssl, imap4);
return FALSE;
}
err = SSL_get_error(imap4->ssl, res);
ERR_error_string(err, buf);
if(res == 0)
{
helper->error(helper->account, buf, 1);
_imap4_stop(imap4);
return FALSE;
}
if(err == SSL_ERROR_WANT_WRITE)
imap4->wr_source = g_io_add_watch(imap4->channel, G_IO_OUT,
_on_watch_can_handshake, imap4);
else if(err == SSL_ERROR_WANT_READ)
imap4->rd_source = g_io_add_watch(imap4->channel, G_IO_IN,
_on_watch_can_handshake, imap4);
else
{
helper->error(helper->account, buf, 1);
_imap4_stop(imap4);
return FALSE;
}
return FALSE;
}
static int _handshake_verify(IMAP4 * imap4)
{
AccountPluginHelper * helper = imap4->helper;
X509 * x509;
char buf[256] = "";
if(SSL_get_verify_result(imap4->ssl) != X509_V_OK)
return helper->confirm(helper->account, "The certificate could"
" not be verified.\nConnect anyway?");
x509 = SSL_get_peer_certificate(imap4->ssl);
X509_NAME_get_text_by_NID(X509_get_subject_name(x509), NID_commonName,
buf, sizeof(buf));
if(strcasecmp(buf, imap4->config[I4CV_HOSTNAME].value) != 0)
return helper->confirm(helper->account, "The certificate could"
" not be matched.\nConnect anyway?");
return 0;
}
/* on_watch_can_read */
static gboolean _on_watch_can_read(GIOChannel * source, GIOCondition condition,
gpointer data)
{
IMAP4 * imap4 = data;
AccountPluginHelper * helper = imap4->helper;
char * p;
gsize cnt = 0;
GError * error = NULL;
GIOStatus status;
IMAP4Command * cmd;
const int inc = 256;
#ifdef DEBUG
fprintf(stderr, "DEBUG: %s()\n", __func__);
#endif
if(condition != G_IO_IN || source != imap4->channel)
return FALSE; /* should not happen */
if((p = realloc(imap4->rd_buf, imap4->rd_buf_cnt + inc)) == NULL)
return TRUE; /* XXX retries immediately (delay?) */
imap4->rd_buf = p;
status = g_io_channel_read_chars(source,
&imap4->rd_buf[imap4->rd_buf_cnt], inc, &cnt, &error);
#ifdef DEBUG
fprintf(stderr, "%s", "DEBUG: IMAP4 SERVER: ");
fwrite(&imap4->rd_buf[imap4->rd_buf_cnt], sizeof(*p), cnt, stderr);
#endif
imap4->rd_buf_cnt += cnt;
switch(status)
{
case G_IO_STATUS_NORMAL:
break;
case G_IO_STATUS_ERROR:
helper->error(helper->account, error->message, 1);
g_error_free(error);
_imap4_stop(imap4);
return FALSE;
case G_IO_STATUS_EOF:
default:
_imap4_event_status(imap4, AS_DISCONNECTED, NULL);
_imap4_stop(imap4);
return FALSE;
}
if(_imap4_parse(imap4) != 0)
{
_imap4_stop(imap4);
return FALSE;
}
if(imap4->queue_cnt == 0)
return TRUE;
cmd = &imap4->queue[0];
if(cmd->buf_cnt == 0)
{
if(cmd->status == I4CS_SENT || cmd->status == I4CS_PARSING)
/* begin or keep parsing */
return TRUE;
else if(cmd->status == I4CS_OK || cmd->status == I4CS_ERROR)
/* the current command is completed */
memmove(cmd, &imap4->queue[1], sizeof(*cmd)
* --imap4->queue_cnt);
}
if(imap4->queue_cnt == 0)
{
_imap4_event_status(imap4, AS_IDLE, NULL);
imap4->source = g_timeout_add(30000, _on_noop, imap4);
}
else
imap4->wr_source = g_io_add_watch(imap4->channel, G_IO_OUT,
_on_watch_can_write, imap4);
return TRUE;
}
/* on_watch_can_read_ssl */
static gboolean _on_watch_can_read_ssl(GIOChannel * source,
GIOCondition condition, gpointer data)
{
IMAP4 * imap4 = data;
char * p;
int cnt;
IMAP4Command * cmd;
char buf[128];
const int inc = 16384; /* XXX not reliable with a smaller value */
#ifdef DEBUG
fprintf(stderr, "DEBUG: %s()\n", __func__);
#endif
if((condition != G_IO_IN && condition != G_IO_OUT)
|| source != imap4->channel)
return FALSE; /* should not happen */
if((p = realloc(imap4->rd_buf, imap4->rd_buf_cnt + inc)) == NULL)
return TRUE; /* XXX retries immediately (delay?) */
imap4->rd_buf = p;
if((cnt = SSL_read(imap4->ssl, &imap4->rd_buf[imap4->rd_buf_cnt], inc))
<= 0)
{
if(SSL_get_error(imap4->ssl, cnt) == SSL_ERROR_WANT_WRITE)
/* call SSL_read() again when it can send data */
imap4->rd_source = g_io_add_watch(imap4->channel,
G_IO_OUT, _on_watch_can_read_ssl,
imap4);
else if(SSL_get_error(imap4->ssl, cnt) == SSL_ERROR_WANT_READ)
/* call SSL_read() again when it can read data */
imap4->rd_source = g_io_add_watch(imap4->channel,
G_IO_IN, _on_watch_can_read_ssl, imap4);
else
{
/* unknown error */
imap4->rd_source = 0;
ERR_error_string(SSL_get_error(imap4->ssl, cnt), buf);
_imap4_event_status(imap4, AS_DISCONNECTED, buf);
_imap4_stop(imap4);
}
return FALSE;
}
#ifdef DEBUG
fprintf(stderr, "%s", "DEBUG: IMAP4 SERVER: ");
fwrite(&imap4->rd_buf[imap4->rd_buf_cnt], sizeof(*p), cnt, stderr);
#endif
imap4->rd_buf_cnt += cnt;
if(_imap4_parse(imap4) != 0)
{
_imap4_stop(imap4);
return FALSE;
}
if(imap4->queue_cnt == 0)
return TRUE;
cmd = &imap4->queue[0];
if(cmd->buf_cnt == 0)
{
if(cmd->status == I4CS_SENT || cmd->status == I4CS_PARSING)
/* begin or keep parsing */
return TRUE;
else if(cmd->status == I4CS_OK || cmd->status == I4CS_ERROR)
/* the current command is completed */
memmove(cmd, &imap4->queue[1], sizeof(*cmd)
* --imap4->queue_cnt);
}
if(imap4->queue_cnt == 0)
{
_imap4_event_status(imap4, AS_IDLE, NULL);
imap4->source = g_timeout_add(30000, _on_noop, imap4);
}
else
imap4->wr_source = g_io_add_watch(imap4->channel, G_IO_OUT,
_on_watch_can_write_ssl, imap4);
return TRUE;
}
/* on_watch_can_write */
static gboolean _on_watch_can_write(GIOChannel * source, GIOCondition condition,
gpointer data)
{
IMAP4 * imap4 = data;
AccountPluginHelper * helper = imap4->helper;
IMAP4Command * cmd = &imap4->queue[0];
gsize cnt = 0;
GError * error = NULL;
GIOStatus status;
char * p;
#ifdef DEBUG
fprintf(stderr, "DEBUG: %s()\n", __func__);
#endif
if(condition != G_IO_OUT || source != imap4->channel
|| imap4->queue_cnt == 0 || cmd->buf_cnt == 0)
return FALSE; /* should not happen */
status = g_io_channel_write_chars(source, cmd->buf, cmd->buf_cnt, &cnt,
&error);
#ifdef DEBUG
fprintf(stderr, "%s", "DEBUG: IMAP4 CLIENT: ");
fwrite(cmd->buf, sizeof(*p), cnt, stderr);
#endif
if(cnt != 0)
{
cmd->buf_cnt -= cnt;
memmove(cmd->buf, &cmd->buf[cnt], cmd->buf_cnt);
if((p = realloc(cmd->buf, cmd->buf_cnt)) != NULL)
cmd->buf = p; /* we can ignore errors... */
else if(cmd->buf_cnt == 0)
cmd->buf = NULL; /* ...except when it's not one */
}
switch(status)
{
case G_IO_STATUS_NORMAL:
break;
case G_IO_STATUS_ERROR:
helper->error(helper->account, error->message, 1);
g_error_free(error);
_imap4_stop(imap4);
return FALSE;
case G_IO_STATUS_EOF:
default:
_imap4_event_status(imap4, AS_DISCONNECTED, NULL);
_imap4_stop(imap4);
return FALSE;
}
if(cmd->buf_cnt > 0)
return TRUE;
cmd->status = I4CS_SENT;
imap4->wr_source = 0;
if(imap4->rd_source == 0)
/* XXX should not happen */
imap4->rd_source = g_io_add_watch(imap4->channel, G_IO_IN,
_on_watch_can_read, imap4);
return FALSE;
}
/* on_watch_can_write_ssl */
static gboolean _on_watch_can_write_ssl(GIOChannel * source,
GIOCondition condition, gpointer data)
{
IMAP4 * imap4 = data;
IMAP4Command * cmd = &imap4->queue[0];
int cnt;
char * p;
char buf[128];
#ifdef DEBUG
fprintf(stderr, "DEBUG: %s()\n", __func__);
#endif
if((condition != G_IO_IN && condition != G_IO_OUT)
|| source != imap4->channel || imap4->queue_cnt == 0
|| cmd->buf_cnt == 0)
return FALSE; /* should not happen */
if((cnt = SSL_write(imap4->ssl, cmd->buf, cmd->buf_cnt)) <= 0)
{
if(SSL_get_error(imap4->ssl, cnt) == SSL_ERROR_WANT_READ)
imap4->wr_source = g_io_add_watch(imap4->channel,
G_IO_IN, _on_watch_can_write_ssl,
imap4);
else if(SSL_get_error(imap4->ssl, cnt) == SSL_ERROR_WANT_WRITE)
imap4->wr_source = g_io_add_watch(imap4->channel,
G_IO_OUT, _on_watch_can_write_ssl,
imap4);
else
{
ERR_error_string(SSL_get_error(imap4->ssl, cnt), buf);
_imap4_event_status(imap4, AS_DISCONNECTED, buf);
_imap4_stop(imap4);
}
return FALSE;
}
#ifdef DEBUG
fprintf(stderr, "%s", "DEBUG: IMAP4 CLIENT: ");
fwrite(cmd->buf, sizeof(*p), cnt, stderr);
#endif
cmd->buf_cnt -= cnt;
memmove(cmd->buf, &cmd->buf[cnt], cmd->buf_cnt);
if((p = realloc(cmd->buf, cmd->buf_cnt)) != NULL)
cmd->buf = p; /* we can ignore errors... */
else if(cmd->buf_cnt == 0)
cmd->buf = NULL; /* ...except when it's not one */
if(cmd->buf_cnt > 0)
return TRUE;
cmd->status = I4CS_SENT;
imap4->wr_source = 0;
if(imap4->rd_source == 0)
/* XXX should not happen */
imap4->rd_source = g_io_add_watch(imap4->channel, G_IO_IN,
_on_watch_can_read_ssl, imap4);
return FALSE;
}
| [
"[email protected]"
] | |
d5a0f6a628b69e87b6869a419f3b56de1371a56f | ca1a8aec7a2251cd2f3254f284cb733ca23e1a0a | /ex10 - Interrupt latency/ex10d_pc1.c | 4176f7f3e8a48d39a25d22de7bfdac1fcb5725a4 | [] | no_license | jd7h/des | 5174493ca16f0db22063c5d83fc079c47ef42a82 | 55c0aa4e456d864810b750e756b13f71f0554fa9 | refs/heads/master | 2020-05-18T03:15:39.533339 | 2015-02-01T21:57:22 | 2015-02-01T21:57:22 | 24,186,373 | 0 | 1 | null | null | null | null | UTF-8 | C | false | false | 2,853 | c | //programma voor PC1
#include <stdio.h>
#include <signal.h>
#include <unistd.h>
#include <sys/mman.h>
#include <native/task.h>
#include <native/timer.h>
#include <native/sem.h>
#include <native/intr.h>
#include <rtdk.h>
#include <sys/io.h>
//interrupt
RT_INTR PC2_intr;
RT_TASK handlertask;
#define PARA_PORT_IRQ 7
#define MEASUREMENTS 10000
#define BASEPERIOD 0
#define PERIOD 1e5 //100 microseconds
int counter = 0;
RTIME results[MEASUREMENTS];
void generate_interrupt_to_pc2()
{
outb(inb(0x378) & 0xfe, 0x378);//set low D0
outb(inb(0x378) | 0x1, 0x378); //set high D0
}
void handler()
{
rt_printf("Begin interrupt handler van PC1\n");
RTIME time1, time2;
while (counter < MEASUREMENTS)
{
time1 = rt_timer_read();
rt_printf("t1:\t%u\n",time1);
rt_printf("Interrupt %d...\n",counter);
generate_interrupt_to_pc2();
int nr_waiting_interrupts = 0;
while(nr_waiting_interrupts <= 0){
nr_waiting_interrupts = rt_intr_wait(&PC2_intr,TM_INFINITE);
if (nr_waiting_interrupts > 0)
{
time2 = rt_timer_read();
rt_printf("Interrupt! Time2: \t%u\n",time2);
}
}
results[counter] = time2-time1;
rt_printf("Writing measurement: %u\n",results[counter]);
counter++;
rt_task_wait_period(NULL);
}
}
void write_RTIMES(char * filename, unsigned int number_of_values,
RTIME *time_values)
{
unsigned int n = 0;
FILE *file;
file = fopen(filename,"w");
while (n<MEASUREMENTS){
fprintf(file,"%u,%llu\n",n,results[n]);
n++;
}
fclose(file);
}
//startup code
void startup()
{
// define interrupt
rt_printf("Creating interrupt...\n");
rt_intr_create(&PC2_intr,NULL,PARA_PORT_IRQ,I_PROPAGATE);
// define interrupt handler
rt_printf("Creating handler task...\n");
rt_task_create(&handlertask,NULL,0,99,T_JOINABLE);
rt_task_set_periodic(&handlertask,TM_NOW,PERIOD);
rt_printf("Starting task...\n");
rt_task_start(&handlertask,&handler,NULL);
rt_task_join(&handlertask);
rt_printf("Done collecting data.");
}
void init_xenomai() {
/* Avoids memory swapping for this program */
mlockall(MCL_CURRENT|MCL_FUTURE);
/* Perform auto-init of rt_print buffers if the task doesn't do so */
rt_print_auto_init(1);
}
void init_ports()
{
ioperm(0x378,1,1);//open port D(0)
ioperm(0x379,1,1);//open port S(6)
ioperm(0x37A,1,1);//open port C(4)
outb(inb(0x37A) | 0x10, 0x37A);//set C4 to high
outb(inb(0x378) | 0x1, 0x378); //set D0 to high
}
void exit_ports(){
//close port D0?
//close port S6?
}
int main(int argc, char* argv[])
{
// code to set things to run xenomai
init_xenomai();
init_ports();
//startup code
startup();
int i;
for (i=0;i<MEASUREMENTS;i++)
{
printf("%d\t%d\n",i,results[i]);
}
write_RTIMES("interrupt_time_diffs_lab_pcs",MEASUREMENTS-1,results);
printf("done exporting results to csv.");
printf("pause\n");
pause();
exit_ports();
}
| [
"[email protected]"
] | |
117306ba311d0623f9a8893255126e6a1de833f4 | df916854176ab539d01ce910d873e38a43ffd8d0 | /Code/Middlewares/Third_Party/lvgl/src/lv_font/font_montserrat_24_tiny.c | ad92fffe2d101a9b665ae9a567daa87f3cf9ef41 | [
"MIT"
] | permissive | LuZening/OPA1000 | 14bb51af58a8d32ba33ab5106dd0578c0a60466d | 64d74c1ba6fc79ecb765368ea7bc234b24e5c4fc | refs/heads/master | 2022-05-08T12:17:01.183583 | 2022-04-04T03:53:26 | 2022-04-04T03:53:26 | 227,651,405 | 0 | 1 | null | null | null | null | UTF-8 | C | false | false | 62,424 | c | /*******************************************************************************
* Size: 24 px
* Bpp: 4
* Opts:
******************************************************************************/
#ifdef LV_LVGL_H_INCLUDE_SIMPLE
#include "lvgl.h"
#else
#include "lvgl/lvgl.h"
#endif
#ifndef FONT_MONTSERRAT_24_TINY
#define FONT_MONTSERRAT_24_TINY 1
#endif
#if FONT_MONTSERRAT_24_TINY
/*-----------------
* BITMAPS
*----------------*/
/*Store the image of the glyphs*/
static LV_ATTRIBUTE_LARGE_CONST const uint8_t glyph_bitmap[] = {
/* U+0020 " " */
/* U+002B "+" */
0x0, 0x0, 0xa, 0xa0, 0x0, 0x0, 0x0, 0x0,
0xf, 0xf0, 0x0, 0x0, 0x0, 0x0, 0xf, 0xf0,
0x0, 0x0, 0x0, 0x0, 0xf, 0xf0, 0x0, 0x0,
0x0, 0x0, 0xf, 0xf0, 0x0, 0x0, 0x6f, 0xff,
0xff, 0xff, 0xff, 0xf5, 0x5e, 0xee, 0xef, 0xfe,
0xee, 0xe5, 0x0, 0x0, 0xf, 0xf0, 0x0, 0x0,
0x0, 0x0, 0xf, 0xf0, 0x0, 0x0, 0x0, 0x0,
0xf, 0xf0, 0x0, 0x0, 0x0, 0x0, 0xf, 0xf0,
0x0, 0x0,
/* U+002C "," */
0x3b, 0x80, 0xcf, 0xf3, 0xaf, 0xf3, 0xf, 0xe0,
0x1f, 0x90, 0x5f, 0x40, 0x9e, 0x0,
/* U+002D "-" */
0x0, 0x0, 0x0, 0xa, 0xff, 0xff, 0xfd, 0xaf,
0xff, 0xff, 0xd0,
/* U+002E "." */
0x4, 0x10, 0x9f, 0xf1, 0xdf, 0xf4, 0x6f, 0xb0,
/* U+0030 "0" */
0x0, 0x1, 0x8d, 0xff, 0xd8, 0x10, 0x0, 0x0,
0x2e, 0xff, 0xff, 0xff, 0xe2, 0x0, 0x1, 0xff,
0xe7, 0x33, 0x7e, 0xff, 0x10, 0xb, 0xfe, 0x20,
0x0, 0x2, 0xef, 0xb0, 0x2f, 0xf5, 0x0, 0x0,
0x0, 0x5f, 0xf2, 0x7f, 0xe0, 0x0, 0x0, 0x0,
0xe, 0xf7, 0xaf, 0xb0, 0x0, 0x0, 0x0, 0xb,
0xfa, 0xcf, 0x90, 0x0, 0x0, 0x0, 0x9, 0xfc,
0xdf, 0x80, 0x0, 0x0, 0x0, 0x8, 0xfd, 0xcf,
0x90, 0x0, 0x0, 0x0, 0x9, 0xfc, 0xaf, 0xb0,
0x0, 0x0, 0x0, 0xb, 0xfa, 0x7f, 0xe0, 0x0,
0x0, 0x0, 0xe, 0xf7, 0x2f, 0xf5, 0x0, 0x0,
0x0, 0x5f, 0xf2, 0xb, 0xfe, 0x10, 0x0, 0x2,
0xef, 0xb0, 0x1, 0xff, 0xe7, 0x33, 0x7e, 0xff,
0x10, 0x0, 0x3e, 0xff, 0xff, 0xff, 0xe2, 0x0,
0x0, 0x1, 0x7c, 0xee, 0xc7, 0x10, 0x0,
/* U+0031 "1" */
0xdf, 0xff, 0xff, 0x5d, 0xff, 0xff, 0xf5, 0x11,
0x11, 0xff, 0x50, 0x0, 0xf, 0xf5, 0x0, 0x0,
0xff, 0x50, 0x0, 0xf, 0xf5, 0x0, 0x0, 0xff,
0x50, 0x0, 0xf, 0xf5, 0x0, 0x0, 0xff, 0x50,
0x0, 0xf, 0xf5, 0x0, 0x0, 0xff, 0x50, 0x0,
0xf, 0xf5, 0x0, 0x0, 0xff, 0x50, 0x0, 0xf,
0xf5, 0x0, 0x0, 0xff, 0x50, 0x0, 0xf, 0xf5,
0x0, 0x0, 0xff, 0x50,
/* U+0032 "2" */
0x0, 0x17, 0xce, 0xfe, 0xc6, 0x0, 0x0, 0x7f,
0xff, 0xff, 0xff, 0xfc, 0x10, 0x6f, 0xfc, 0x63,
0x35, 0xbf, 0xfa, 0x0, 0x97, 0x0, 0x0, 0x0,
0xaf, 0xf1, 0x0, 0x0, 0x0, 0x0, 0x3, 0xff,
0x30, 0x0, 0x0, 0x0, 0x0, 0x3f, 0xf2, 0x0,
0x0, 0x0, 0x0, 0x8, 0xfe, 0x0, 0x0, 0x0,
0x0, 0x2, 0xff, 0x70, 0x0, 0x0, 0x0, 0x2,
0xef, 0xc0, 0x0, 0x0, 0x0, 0x2, 0xef, 0xd1,
0x0, 0x0, 0x0, 0x2, 0xef, 0xd1, 0x0, 0x0,
0x0, 0x3, 0xef, 0xc1, 0x0, 0x0, 0x0, 0x3,
0xef, 0xc0, 0x0, 0x0, 0x0, 0x3, 0xff, 0xb0,
0x0, 0x0, 0x0, 0x4, 0xff, 0xc2, 0x11, 0x11,
0x11, 0x11, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0x1f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xf0,
/* U+0033 "3" */
0x1f, 0xff, 0xff, 0xff, 0xff, 0xff, 0x1, 0xff,
0xff, 0xff, 0xff, 0xff, 0xe0, 0x1, 0x11, 0x11,
0x11, 0x7f, 0xf4, 0x0, 0x0, 0x0, 0x0, 0x3f,
0xf7, 0x0, 0x0, 0x0, 0x0, 0x1e, 0xfa, 0x0,
0x0, 0x0, 0x0, 0xc, 0xfd, 0x0, 0x0, 0x0,
0x0, 0x9, 0xfe, 0x20, 0x0, 0x0, 0x0, 0x3,
0xff, 0xfc, 0x71, 0x0, 0x0, 0x0, 0x3f, 0xff,
0xff, 0xe3, 0x0, 0x0, 0x0, 0x0, 0x15, 0xef,
0xe1, 0x0, 0x0, 0x0, 0x0, 0x2, 0xff, 0x60,
0x0, 0x0, 0x0, 0x0, 0xc, 0xf9, 0x0, 0x0,
0x0, 0x0, 0x0, 0xdf, 0x81, 0xa1, 0x0, 0x0,
0x0, 0x4f, 0xf5, 0x9f, 0xfa, 0x53, 0x34, 0x9f,
0xfd, 0x3, 0xdf, 0xff, 0xff, 0xff, 0xfd, 0x20,
0x0, 0x49, 0xdf, 0xfe, 0xb6, 0x0, 0x0,
/* U+0034 "4" */
0x0, 0x0, 0x0, 0x0, 0xd, 0xfb, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0xaf, 0xe1, 0x0, 0x0,
0x0, 0x0, 0x0, 0x6, 0xff, 0x30, 0x0, 0x0,
0x0, 0x0, 0x0, 0x3f, 0xf7, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0xdf, 0xb0, 0x0, 0x0, 0x0,
0x0, 0x0, 0xa, 0xfd, 0x10, 0x0, 0x0, 0x0,
0x0, 0x0, 0x7f, 0xf3, 0x0, 0x0, 0x0, 0x0,
0x0, 0x3, 0xff, 0x60, 0x0, 0x9d, 0x70, 0x0,
0x0, 0x1e, 0xfa, 0x0, 0x0, 0xbf, 0x90, 0x0,
0x0, 0xbf, 0xd0, 0x0, 0x0, 0xbf, 0x90, 0x0,
0x7, 0xff, 0x41, 0x11, 0x11, 0xbf, 0x91, 0x11,
0x1f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfc,
0x1f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfc,
0x0, 0x0, 0x0, 0x0, 0x0, 0xcf, 0x90, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0xcf, 0x90, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0xcf, 0x90, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0xcf, 0x90, 0x0,
/* U+0035 "5" */
0x0, 0x8f, 0xff, 0xff, 0xff, 0xff, 0x0, 0xa,
0xff, 0xff, 0xff, 0xff, 0xf0, 0x0, 0xbf, 0x81,
0x11, 0x11, 0x11, 0x0, 0xd, 0xf6, 0x0, 0x0,
0x0, 0x0, 0x0, 0xef, 0x40, 0x0, 0x0, 0x0,
0x0, 0xf, 0xf3, 0x0, 0x0, 0x0, 0x0, 0x2,
0xff, 0x31, 0x10, 0x0, 0x0, 0x0, 0x3f, 0xff,
0xff, 0xfe, 0xa3, 0x0, 0x5, 0xff, 0xff, 0xff,
0xff, 0xf8, 0x0, 0x0, 0x0, 0x0, 0x26, 0xdf,
0xf5, 0x0, 0x0, 0x0, 0x0, 0x0, 0xdf, 0xb0,
0x0, 0x0, 0x0, 0x0, 0x8, 0xfe, 0x0, 0x0,
0x0, 0x0, 0x0, 0x8f, 0xd0, 0x93, 0x0, 0x0,
0x0, 0x1e, 0xfa, 0x5f, 0xfb, 0x63, 0x24, 0x7e,
0xff, 0x31, 0xbf, 0xff, 0xff, 0xff, 0xff, 0x50,
0x0, 0x28, 0xce, 0xfe, 0xc8, 0x10, 0x0,
/* U+0036 "6" */
0x0, 0x0, 0x4a, 0xdf, 0xfe, 0xb5, 0x0, 0x0,
0xa, 0xff, 0xff, 0xff, 0xff, 0x10, 0x0, 0xcf,
0xf9, 0x42, 0x23, 0x76, 0x0, 0x8, 0xfe, 0x30,
0x0, 0x0, 0x0, 0x0, 0x1f, 0xf5, 0x0, 0x0,
0x0, 0x0, 0x0, 0x6f, 0xe0, 0x0, 0x0, 0x0,
0x0, 0x0, 0xaf, 0xa0, 0x5b, 0xef, 0xd9, 0x30,
0x0, 0xbf, 0x9a, 0xff, 0xff, 0xff, 0xf7, 0x0,
0xdf, 0xff, 0xc4, 0x1, 0x4c, 0xff, 0x40, 0xcf,
0xfc, 0x0, 0x0, 0x0, 0xcf, 0xc0, 0xbf, 0xf5,
0x0, 0x0, 0x0, 0x5f, 0xf0, 0x8f, 0xf2, 0x0,
0x0, 0x0, 0x3f, 0xf1, 0x4f, 0xf4, 0x0, 0x0,
0x0, 0x4f, 0xf0, 0xd, 0xfc, 0x0, 0x0, 0x0,
0xbf, 0xb0, 0x4, 0xff, 0xc3, 0x0, 0x3b, 0xff,
0x30, 0x0, 0x5f, 0xff, 0xff, 0xff, 0xf5, 0x0,
0x0, 0x1, 0x8d, 0xff, 0xd9, 0x20, 0x0,
/* U+0037 "7" */
0x4f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xf6, 0x4f,
0xff, 0xff, 0xff, 0xff, 0xff, 0xf5, 0x4f, 0xf2,
0x11, 0x11, 0x11, 0x8f, 0xf1, 0x4f, 0xf0, 0x0,
0x0, 0x0, 0xef, 0x90, 0x4f, 0xf0, 0x0, 0x0,
0x5, 0xff, 0x20, 0x2, 0x20, 0x0, 0x0, 0xc,
0xfa, 0x0, 0x0, 0x0, 0x0, 0x0, 0x4f, 0xf3,
0x0, 0x0, 0x0, 0x0, 0x0, 0xbf, 0xc0, 0x0,
0x0, 0x0, 0x0, 0x2, 0xff, 0x50, 0x0, 0x0,
0x0, 0x0, 0x9, 0xfe, 0x0, 0x0, 0x0, 0x0,
0x0, 0x1f, 0xf7, 0x0, 0x0, 0x0, 0x0, 0x0,
0x7f, 0xf1, 0x0, 0x0, 0x0, 0x0, 0x0, 0xef,
0x90, 0x0, 0x0, 0x0, 0x0, 0x6, 0xff, 0x20,
0x0, 0x0, 0x0, 0x0, 0xd, 0xfb, 0x0, 0x0,
0x0, 0x0, 0x0, 0x4f, 0xf4, 0x0, 0x0, 0x0,
0x0, 0x0, 0xbf, 0xd0, 0x0, 0x0, 0x0,
/* U+0038 "8" */
0x0, 0x6, 0xbe, 0xff, 0xd9, 0x20, 0x0, 0x2,
0xdf, 0xff, 0xff, 0xff, 0xf7, 0x0, 0xd, 0xff,
0x71, 0x0, 0x4b, 0xff, 0x40, 0x3f, 0xf5, 0x0,
0x0, 0x0, 0xcf, 0xa0, 0x4f, 0xf1, 0x0, 0x0,
0x0, 0x9f, 0xc0, 0x2f, 0xf5, 0x0, 0x0, 0x0,
0xdf, 0x90, 0xa, 0xff, 0x72, 0x1, 0x4c, 0xff,
0x20, 0x0, 0x8f, 0xff, 0xff, 0xff, 0xd3, 0x0,
0x4, 0xdf, 0xff, 0xef, 0xff, 0xf8, 0x0, 0x2f,
0xfc, 0x40, 0x0, 0x18, 0xff, 0x90, 0xaf, 0xd0,
0x0, 0x0, 0x0, 0x6f, 0xf2, 0xdf, 0x80, 0x0,
0x0, 0x0, 0xf, 0xf5, 0xdf, 0x80, 0x0, 0x0,
0x0, 0x1f, 0xf5, 0xaf, 0xe1, 0x0, 0x0, 0x0,
0x8f, 0xf2, 0x3f, 0xfd, 0x51, 0x0, 0x3a, 0xff,
0xa0, 0x5, 0xff, 0xff, 0xff, 0xff, 0xfa, 0x0,
0x0, 0x17, 0xce, 0xff, 0xd9, 0x40, 0x0,
/* U+0039 "9" */
0x0, 0x4, 0xae, 0xfe, 0xc7, 0x0, 0x0, 0x0,
0xaf, 0xff, 0xff, 0xff, 0xe2, 0x0, 0x8, 0xff,
0x82, 0x0, 0x4c, 0xfe, 0x10, 0x1f, 0xf6, 0x0,
0x0, 0x0, 0xcf, 0xa0, 0x3f, 0xf0, 0x0, 0x0,
0x0, 0x6f, 0xf1, 0x4f, 0xf0, 0x0, 0x0, 0x0,
0x6f, 0xf5, 0x1f, 0xf6, 0x0, 0x0, 0x0, 0xcf,
0xf8, 0xa, 0xff, 0x82, 0x0, 0x4c, 0xff, 0xf9,
0x0, 0xcf, 0xff, 0xff, 0xff, 0x9c, 0xfa, 0x0,
0x6, 0xbe, 0xfe, 0xa4, 0xd, 0xf8, 0x0, 0x0,
0x0, 0x0, 0x0, 0xf, 0xf7, 0x0, 0x0, 0x0,
0x0, 0x0, 0x3f, 0xf2, 0x0, 0x0, 0x0, 0x0,
0x0, 0xbf, 0xd0, 0x0, 0x0, 0x0, 0x0, 0x8,
0xff, 0x50, 0x0, 0xa7, 0x31, 0x25, 0xcf, 0xf9,
0x0, 0x3, 0xff, 0xff, 0xff, 0xff, 0x80, 0x0,
0x0, 0x7b, 0xdf, 0xec, 0x82, 0x0, 0x0,
/* U+0041 "A" */
0x0, 0x0, 0x0, 0x0, 0xaf, 0xf2, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x1f, 0xff, 0xa0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x8, 0xfe,
0xff, 0x10, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0xff, 0x5d, 0xf8, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x7f, 0xe0, 0x6f, 0xe0, 0x0, 0x0, 0x0,
0x0, 0x0, 0xd, 0xf7, 0x0, 0xef, 0x60, 0x0,
0x0, 0x0, 0x0, 0x5, 0xff, 0x10, 0x8, 0xfd,
0x0, 0x0, 0x0, 0x0, 0x0, 0xcf, 0xa0, 0x0,
0x1f, 0xf5, 0x0, 0x0, 0x0, 0x0, 0x3f, 0xf3,
0x0, 0x0, 0xaf, 0xc0, 0x0, 0x0, 0x0, 0xa,
0xfc, 0x0, 0x0, 0x4, 0xff, 0x30, 0x0, 0x0,
0x2, 0xff, 0x50, 0x0, 0x0, 0xd, 0xfa, 0x0,
0x0, 0x0, 0x9f, 0xff, 0xff, 0xff, 0xff, 0xff,
0xf2, 0x0, 0x0, 0x1f, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0x90, 0x0, 0x7, 0xff, 0x10, 0x0,
0x0, 0x0, 0x8, 0xff, 0x10, 0x0, 0xef, 0x90,
0x0, 0x0, 0x0, 0x0, 0x1f, 0xf7, 0x0, 0x5f,
0xf2, 0x0, 0x0, 0x0, 0x0, 0x0, 0x9f, 0xe0,
0xc, 0xfa, 0x0, 0x0, 0x0, 0x0, 0x0, 0x2,
0xff, 0x50,
/* U+0042 "B" */
0x7f, 0xff, 0xff, 0xff, 0xfe, 0xb6, 0x0, 0x7,
0xff, 0xff, 0xff, 0xff, 0xff, 0xfd, 0x10, 0x7f,
0xe0, 0x0, 0x0, 0x2, 0x9f, 0xfa, 0x7, 0xfe,
0x0, 0x0, 0x0, 0x0, 0x9f, 0xf0, 0x7f, 0xe0,
0x0, 0x0, 0x0, 0x5, 0xff, 0x7, 0xfe, 0x0,
0x0, 0x0, 0x0, 0x9f, 0xd0, 0x7f, 0xe0, 0x0,
0x0, 0x2, 0x9f, 0xf5, 0x7, 0xff, 0xff, 0xff,
0xff, 0xff, 0xf6, 0x0, 0x7f, 0xff, 0xff, 0xff,
0xff, 0xff, 0xd4, 0x7, 0xfe, 0x0, 0x0, 0x0,
0x14, 0xcf, 0xf3, 0x7f, 0xe0, 0x0, 0x0, 0x0,
0x0, 0xdf, 0xa7, 0xfe, 0x0, 0x0, 0x0, 0x0,
0x8, 0xfd, 0x7f, 0xe0, 0x0, 0x0, 0x0, 0x0,
0x8f, 0xe7, 0xfe, 0x0, 0x0, 0x0, 0x0, 0xc,
0xfc, 0x7f, 0xe0, 0x0, 0x0, 0x0, 0x3b, 0xff,
0x67, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x90,
0x7f, 0xff, 0xff, 0xff, 0xff, 0xd9, 0x30, 0x0,
/* U+0043 "C" */
0x0, 0x0, 0x5, 0xad, 0xff, 0xda, 0x50, 0x0,
0x0, 0x3, 0xdf, 0xff, 0xff, 0xff, 0xfd, 0x30,
0x0, 0x5f, 0xff, 0xb6, 0x43, 0x59, 0xff, 0xf2,
0x3, 0xff, 0xd3, 0x0, 0x0, 0x0, 0x1c, 0x80,
0xd, 0xfe, 0x10, 0x0, 0x0, 0x0, 0x0, 0x0,
0x5f, 0xf4, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x9f, 0xe0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0xcf, 0xa0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0xdf, 0x90, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0xcf, 0xa0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x9f, 0xd0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x5f, 0xf4, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0xd, 0xfe, 0x10, 0x0, 0x0, 0x0, 0x0, 0x0,
0x3, 0xff, 0xd3, 0x0, 0x0, 0x0, 0x1c, 0x80,
0x0, 0x5f, 0xff, 0xb5, 0x33, 0x49, 0xff, 0xf2,
0x0, 0x3, 0xdf, 0xff, 0xff, 0xff, 0xfd, 0x30,
0x0, 0x0, 0x5, 0xae, 0xff, 0xda, 0x50, 0x0,
/* U+0044 "D" */
0x7f, 0xff, 0xff, 0xff, 0xfd, 0x94, 0x0, 0x0,
0x7, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfc, 0x20,
0x0, 0x7f, 0xe1, 0x11, 0x12, 0x36, 0xbf, 0xff,
0x40, 0x7, 0xfe, 0x0, 0x0, 0x0, 0x0, 0x4e,
0xfe, 0x20, 0x7f, 0xe0, 0x0, 0x0, 0x0, 0x0,
0x2f, 0xfb, 0x7, 0xfe, 0x0, 0x0, 0x0, 0x0,
0x0, 0x7f, 0xf2, 0x7f, 0xe0, 0x0, 0x0, 0x0,
0x0, 0x1, 0xff, 0x77, 0xfe, 0x0, 0x0, 0x0,
0x0, 0x0, 0xd, 0xf9, 0x7f, 0xe0, 0x0, 0x0,
0x0, 0x0, 0x0, 0xcf, 0xa7, 0xfe, 0x0, 0x0,
0x0, 0x0, 0x0, 0xd, 0xf9, 0x7f, 0xe0, 0x0,
0x0, 0x0, 0x0, 0x1, 0xff, 0x77, 0xfe, 0x0,
0x0, 0x0, 0x0, 0x0, 0x7f, 0xf2, 0x7f, 0xe0,
0x0, 0x0, 0x0, 0x0, 0x2f, 0xfb, 0x7, 0xfe,
0x0, 0x0, 0x0, 0x0, 0x3e, 0xfe, 0x20, 0x7f,
0xe1, 0x11, 0x11, 0x35, 0xbf, 0xff, 0x40, 0x7,
0xff, 0xff, 0xff, 0xff, 0xff, 0xfc, 0x20, 0x0,
0x7f, 0xff, 0xff, 0xff, 0xfd, 0x94, 0x0, 0x0,
0x0,
/* U+0045 "E" */
0x7f, 0xff, 0xff, 0xff, 0xff, 0xff, 0x67, 0xff,
0xff, 0xff, 0xff, 0xff, 0xf6, 0x7f, 0xe1, 0x11,
0x11, 0x11, 0x11, 0x7, 0xfe, 0x0, 0x0, 0x0,
0x0, 0x0, 0x7f, 0xe0, 0x0, 0x0, 0x0, 0x0,
0x7, 0xfe, 0x0, 0x0, 0x0, 0x0, 0x0, 0x7f,
0xe0, 0x0, 0x0, 0x0, 0x0, 0x7, 0xff, 0xff,
0xff, 0xff, 0xff, 0x50, 0x7f, 0xff, 0xff, 0xff,
0xff, 0xf5, 0x7, 0xfe, 0x11, 0x11, 0x11, 0x11,
0x0, 0x7f, 0xe0, 0x0, 0x0, 0x0, 0x0, 0x7,
0xfe, 0x0, 0x0, 0x0, 0x0, 0x0, 0x7f, 0xe0,
0x0, 0x0, 0x0, 0x0, 0x7, 0xfe, 0x0, 0x0,
0x0, 0x0, 0x0, 0x7f, 0xe1, 0x11, 0x11, 0x11,
0x11, 0x17, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfb,
0x7f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xb0,
/* U+0046 "F" */
0x7f, 0xff, 0xff, 0xff, 0xff, 0xff, 0x67, 0xff,
0xff, 0xff, 0xff, 0xff, 0xf6, 0x7f, 0xe1, 0x11,
0x11, 0x11, 0x11, 0x7, 0xfe, 0x0, 0x0, 0x0,
0x0, 0x0, 0x7f, 0xe0, 0x0, 0x0, 0x0, 0x0,
0x7, 0xfe, 0x0, 0x0, 0x0, 0x0, 0x0, 0x7f,
0xe0, 0x0, 0x0, 0x0, 0x0, 0x7, 0xfe, 0x0,
0x0, 0x0, 0x0, 0x0, 0x7f, 0xff, 0xff, 0xff,
0xff, 0xf5, 0x7, 0xff, 0xff, 0xff, 0xff, 0xff,
0x50, 0x7f, 0xe1, 0x11, 0x11, 0x11, 0x10, 0x7,
0xfe, 0x0, 0x0, 0x0, 0x0, 0x0, 0x7f, 0xe0,
0x0, 0x0, 0x0, 0x0, 0x7, 0xfe, 0x0, 0x0,
0x0, 0x0, 0x0, 0x7f, 0xe0, 0x0, 0x0, 0x0,
0x0, 0x7, 0xfe, 0x0, 0x0, 0x0, 0x0, 0x0,
0x7f, 0xe0, 0x0, 0x0, 0x0, 0x0, 0x0,
/* U+0047 "G" */
0x0, 0x0, 0x5, 0xad, 0xff, 0xeb, 0x60, 0x0,
0x0, 0x3, 0xdf, 0xff, 0xff, 0xff, 0xfe, 0x50,
0x0, 0x5f, 0xff, 0xb6, 0x43, 0x48, 0xef, 0xf5,
0x3, 0xff, 0xd3, 0x0, 0x0, 0x0, 0x9, 0xb0,
0xd, 0xfe, 0x10, 0x0, 0x0, 0x0, 0x0, 0x0,
0x5f, 0xf5, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x9f, 0xe0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0xcf, 0xa0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0xdf, 0x90, 0x0, 0x0, 0x0, 0x0, 0x7, 0x94,
0xcf, 0xa0, 0x0, 0x0, 0x0, 0x0, 0xd, 0xf7,
0x9f, 0xe0, 0x0, 0x0, 0x0, 0x0, 0xd, 0xf7,
0x5f, 0xf5, 0x0, 0x0, 0x0, 0x0, 0xd, 0xf7,
0xd, 0xfe, 0x10, 0x0, 0x0, 0x0, 0xd, 0xf7,
0x3, 0xff, 0xd3, 0x0, 0x0, 0x0, 0xd, 0xf7,
0x0, 0x5f, 0xff, 0xb6, 0x32, 0x47, 0xdf, 0xf7,
0x0, 0x3, 0xdf, 0xff, 0xff, 0xff, 0xff, 0x80,
0x0, 0x0, 0x5, 0xad, 0xff, 0xeb, 0x71, 0x0,
/* U+0048 "H" */
0x7f, 0xe0, 0x0, 0x0, 0x0, 0x0, 0x7f, 0xf7,
0xfe, 0x0, 0x0, 0x0, 0x0, 0x7, 0xff, 0x7f,
0xe0, 0x0, 0x0, 0x0, 0x0, 0x7f, 0xf7, 0xfe,
0x0, 0x0, 0x0, 0x0, 0x7, 0xff, 0x7f, 0xe0,
0x0, 0x0, 0x0, 0x0, 0x7f, 0xf7, 0xfe, 0x0,
0x0, 0x0, 0x0, 0x7, 0xff, 0x7f, 0xe0, 0x0,
0x0, 0x0, 0x0, 0x7f, 0xf7, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0x7f, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xf7, 0xfe, 0x11, 0x11, 0x11,
0x11, 0x17, 0xff, 0x7f, 0xe0, 0x0, 0x0, 0x0,
0x0, 0x7f, 0xf7, 0xfe, 0x0, 0x0, 0x0, 0x0,
0x7, 0xff, 0x7f, 0xe0, 0x0, 0x0, 0x0, 0x0,
0x7f, 0xf7, 0xfe, 0x0, 0x0, 0x0, 0x0, 0x7,
0xff, 0x7f, 0xe0, 0x0, 0x0, 0x0, 0x0, 0x7f,
0xf7, 0xfe, 0x0, 0x0, 0x0, 0x0, 0x7, 0xff,
0x7f, 0xe0, 0x0, 0x0, 0x0, 0x0, 0x7f, 0xf0,
/* U+0049 "I" */
0x7f, 0xe7, 0xfe, 0x7f, 0xe7, 0xfe, 0x7f, 0xe7,
0xfe, 0x7f, 0xe7, 0xfe, 0x7f, 0xe7, 0xfe, 0x7f,
0xe7, 0xfe, 0x7f, 0xe7, 0xfe, 0x7f, 0xe7, 0xfe,
0x7f, 0xe0,
/* U+004A "J" */
0x0, 0x8f, 0xff, 0xff, 0xff, 0xf0, 0x8, 0xff,
0xff, 0xff, 0xff, 0x0, 0x1, 0x11, 0x11, 0x7f,
0xf0, 0x0, 0x0, 0x0, 0x7, 0xff, 0x0, 0x0,
0x0, 0x0, 0x7f, 0xf0, 0x0, 0x0, 0x0, 0x7,
0xff, 0x0, 0x0, 0x0, 0x0, 0x7f, 0xf0, 0x0,
0x0, 0x0, 0x7, 0xff, 0x0, 0x0, 0x0, 0x0,
0x7f, 0xf0, 0x0, 0x0, 0x0, 0x7, 0xff, 0x0,
0x0, 0x0, 0x0, 0x7f, 0xf0, 0x0, 0x0, 0x0,
0x7, 0xfe, 0x0, 0x0, 0x0, 0x0, 0x8f, 0xd0,
0x5a, 0x0, 0x0, 0xd, 0xfa, 0xf, 0xfc, 0x41,
0x3b, 0xff, 0x50, 0x5f, 0xff, 0xff, 0xff, 0xa0,
0x0, 0x29, 0xdf, 0xfc, 0x60, 0x0,
/* U+004B "K" */
0x7f, 0xe0, 0x0, 0x0, 0x0, 0x6, 0xff, 0x50,
0x7f, 0xe0, 0x0, 0x0, 0x0, 0x6f, 0xf6, 0x0,
0x7f, 0xe0, 0x0, 0x0, 0x5, 0xff, 0x60, 0x0,
0x7f, 0xe0, 0x0, 0x0, 0x5f, 0xf7, 0x0, 0x0,
0x7f, 0xe0, 0x0, 0x4, 0xff, 0x80, 0x0, 0x0,
0x7f, 0xe0, 0x0, 0x4f, 0xf9, 0x0, 0x0, 0x0,
0x7f, 0xe0, 0x3, 0xff, 0xa0, 0x0, 0x0, 0x0,
0x7f, 0xe0, 0x3f, 0xfd, 0x0, 0x0, 0x0, 0x0,
0x7f, 0xe3, 0xef, 0xff, 0x40, 0x0, 0x0, 0x0,
0x7f, 0xfe, 0xfd, 0xdf, 0xf2, 0x0, 0x0, 0x0,
0x7f, 0xff, 0xd1, 0x2f, 0xfd, 0x10, 0x0, 0x0,
0x7f, 0xfe, 0x10, 0x4, 0xff, 0xb0, 0x0, 0x0,
0x7f, 0xf2, 0x0, 0x0, 0x6f, 0xf8, 0x0, 0x0,
0x7f, 0xe0, 0x0, 0x0, 0x8, 0xff, 0x50, 0x0,
0x7f, 0xe0, 0x0, 0x0, 0x0, 0xbf, 0xf3, 0x0,
0x7f, 0xe0, 0x0, 0x0, 0x0, 0xc, 0xfe, 0x10,
0x7f, 0xe0, 0x0, 0x0, 0x0, 0x1, 0xef, 0xc0,
/* U+004C "L" */
0x7f, 0xe0, 0x0, 0x0, 0x0, 0x0, 0x7, 0xfe,
0x0, 0x0, 0x0, 0x0, 0x0, 0x7f, 0xe0, 0x0,
0x0, 0x0, 0x0, 0x7, 0xfe, 0x0, 0x0, 0x0,
0x0, 0x0, 0x7f, 0xe0, 0x0, 0x0, 0x0, 0x0,
0x7, 0xfe, 0x0, 0x0, 0x0, 0x0, 0x0, 0x7f,
0xe0, 0x0, 0x0, 0x0, 0x0, 0x7, 0xfe, 0x0,
0x0, 0x0, 0x0, 0x0, 0x7f, 0xe0, 0x0, 0x0,
0x0, 0x0, 0x7, 0xfe, 0x0, 0x0, 0x0, 0x0,
0x0, 0x7f, 0xe0, 0x0, 0x0, 0x0, 0x0, 0x7,
0xfe, 0x0, 0x0, 0x0, 0x0, 0x0, 0x7f, 0xe0,
0x0, 0x0, 0x0, 0x0, 0x7, 0xfe, 0x0, 0x0,
0x0, 0x0, 0x0, 0x7f, 0xe1, 0x11, 0x11, 0x11,
0x11, 0x7, 0xff, 0xff, 0xff, 0xff, 0xff, 0xf0,
0x7f, 0xff, 0xff, 0xff, 0xff, 0xff, 0x0,
/* U+004D "M" */
0x7f, 0xc0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0xdf, 0x67, 0xff, 0x50, 0x0, 0x0, 0x0, 0x0,
0x0, 0x7f, 0xf6, 0x7f, 0xfe, 0x0, 0x0, 0x0,
0x0, 0x0, 0x1f, 0xff, 0x67, 0xff, 0xf8, 0x0,
0x0, 0x0, 0x0, 0x9, 0xff, 0xf6, 0x7f, 0xff,
0xf2, 0x0, 0x0, 0x0, 0x3, 0xff, 0xff, 0x67,
0xfd, 0xbf, 0xb0, 0x0, 0x0, 0x0, 0xcf, 0x8e,
0xf6, 0x7f, 0xd2, 0xff, 0x40, 0x0, 0x0, 0x5f,
0xe0, 0xef, 0x67, 0xfd, 0x8, 0xfd, 0x0, 0x0,
0xe, 0xf6, 0xe, 0xf6, 0x7f, 0xd0, 0xe, 0xf7,
0x0, 0x8, 0xfc, 0x0, 0xef, 0x67, 0xfd, 0x0,
0x5f, 0xf1, 0x1, 0xff, 0x30, 0xe, 0xf6, 0x7f,
0xd0, 0x0, 0xbf, 0xa0, 0xaf, 0x90, 0x0, 0xef,
0x67, 0xfd, 0x0, 0x2, 0xff, 0x7f, 0xe1, 0x0,
0xe, 0xf6, 0x7f, 0xd0, 0x0, 0x8, 0xff, 0xf6,
0x0, 0x0, 0xef, 0x67, 0xfd, 0x0, 0x0, 0xe,
0xfd, 0x0, 0x0, 0xe, 0xf6, 0x7f, 0xd0, 0x0,
0x0, 0x5f, 0x40, 0x0, 0x0, 0xef, 0x67, 0xfd,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xe, 0xf6,
0x7f, 0xd0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0xef, 0x60,
/* U+004E "N" */
0x7f, 0xd0, 0x0, 0x0, 0x0, 0x0, 0x7f, 0xf7,
0xff, 0xa0, 0x0, 0x0, 0x0, 0x7, 0xff, 0x7f,
0xff, 0x70, 0x0, 0x0, 0x0, 0x7f, 0xf7, 0xff,
0xff, 0x40, 0x0, 0x0, 0x7, 0xff, 0x7f, 0xfd,
0xfe, 0x20, 0x0, 0x0, 0x7f, 0xf7, 0xfe, 0x3f,
0xfd, 0x0, 0x0, 0x7, 0xff, 0x7f, 0xe0, 0x5f,
0xfa, 0x0, 0x0, 0x7f, 0xf7, 0xfe, 0x0, 0x8f,
0xf7, 0x0, 0x7, 0xff, 0x7f, 0xe0, 0x0, 0xbf,
0xf4, 0x0, 0x7f, 0xf7, 0xfe, 0x0, 0x1, 0xef,
0xe1, 0x7, 0xff, 0x7f, 0xe0, 0x0, 0x3, 0xff,
0xc0, 0x7f, 0xf7, 0xfe, 0x0, 0x0, 0x6, 0xff,
0xa7, 0xff, 0x7f, 0xe0, 0x0, 0x0, 0x9, 0xff,
0xdf, 0xf7, 0xfe, 0x0, 0x0, 0x0, 0xc, 0xff,
0xff, 0x7f, 0xe0, 0x0, 0x0, 0x0, 0x1e, 0xff,
0xf7, 0xfe, 0x0, 0x0, 0x0, 0x0, 0x3f, 0xff,
0x7f, 0xe0, 0x0, 0x0, 0x0, 0x0, 0x6f, 0xf0,
/* U+004F "O" */
0x0, 0x0, 0x5, 0xad, 0xff, 0xeb, 0x60, 0x0,
0x0, 0x0, 0x0, 0x2d, 0xff, 0xff, 0xff, 0xff,
0xe4, 0x0, 0x0, 0x0, 0x5f, 0xff, 0xb6, 0x33,
0x5a, 0xff, 0xf7, 0x0, 0x0, 0x3f, 0xfd, 0x30,
0x0, 0x0, 0x1, 0xcf, 0xf5, 0x0, 0xd, 0xfe,
0x10, 0x0, 0x0, 0x0, 0x0, 0xcf, 0xf1, 0x4,
0xff, 0x40, 0x0, 0x0, 0x0, 0x0, 0x2, 0xff,
0x70, 0x9f, 0xe0, 0x0, 0x0, 0x0, 0x0, 0x0,
0xb, 0xfc, 0xc, 0xfa, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x8f, 0xf0, 0xdf, 0x90, 0x0, 0x0,
0x0, 0x0, 0x0, 0x6, 0xff, 0xc, 0xfa, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x8f, 0xf0, 0x9f,
0xd0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xb, 0xfc,
0x5, 0xff, 0x40, 0x0, 0x0, 0x0, 0x0, 0x2,
0xff, 0x70, 0xd, 0xfe, 0x10, 0x0, 0x0, 0x0,
0x0, 0xcf, 0xf1, 0x0, 0x3f, 0xfd, 0x30, 0x0,
0x0, 0x1, 0xcf, 0xf5, 0x0, 0x0, 0x5f, 0xff,
0xb5, 0x33, 0x59, 0xff, 0xf8, 0x0, 0x0, 0x0,
0x3d, 0xff, 0xff, 0xff, 0xff, 0xe4, 0x0, 0x0,
0x0, 0x0, 0x5, 0xad, 0xff, 0xeb, 0x60, 0x0,
0x0, 0x0,
/* U+0050 "P" */
0x7f, 0xff, 0xff, 0xff, 0xeb, 0x60, 0x0, 0x7,
0xff, 0xff, 0xff, 0xff, 0xff, 0xd2, 0x0, 0x7f,
0xe1, 0x11, 0x12, 0x49, 0xff, 0xe1, 0x7, 0xfe,
0x0, 0x0, 0x0, 0x3, 0xff, 0x90, 0x7f, 0xe0,
0x0, 0x0, 0x0, 0x9, 0xfe, 0x7, 0xfe, 0x0,
0x0, 0x0, 0x0, 0x5f, 0xf0, 0x7f, 0xe0, 0x0,
0x0, 0x0, 0x5, 0xff, 0x7, 0xfe, 0x0, 0x0,
0x0, 0x0, 0x9f, 0xe0, 0x7f, 0xe0, 0x0, 0x0,
0x0, 0x3f, 0xf9, 0x7, 0xfe, 0x11, 0x11, 0x24,
0x8f, 0xfe, 0x10, 0x7f, 0xff, 0xff, 0xff, 0xff,
0xfd, 0x20, 0x7, 0xff, 0xff, 0xff, 0xfe, 0xb6,
0x0, 0x0, 0x7f, 0xe0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x7, 0xfe, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x7f, 0xe0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x7, 0xfe, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x7f, 0xe0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
/* U+0051 "Q" */
0x0, 0x0, 0x5, 0xad, 0xff, 0xeb, 0x60, 0x0,
0x0, 0x0, 0x0, 0x2d, 0xff, 0xff, 0xff, 0xff,
0xe4, 0x0, 0x0, 0x0, 0x5f, 0xff, 0xb6, 0x33,
0x5a, 0xff, 0xf7, 0x0, 0x0, 0x2f, 0xfd, 0x30,
0x0, 0x0, 0x2, 0xcf, 0xf5, 0x0, 0xd, 0xfe,
0x10, 0x0, 0x0, 0x0, 0x0, 0xdf, 0xf1, 0x4,
0xff, 0x50, 0x0, 0x0, 0x0, 0x0, 0x2, 0xff,
0x70, 0x9f, 0xe0, 0x0, 0x0, 0x0, 0x0, 0x0,
0xb, 0xfc, 0xc, 0xfa, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x8f, 0xf0, 0xdf, 0x90, 0x0, 0x0,
0x0, 0x0, 0x0, 0x6, 0xff, 0xc, 0xfa, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x8f, 0xe0, 0xaf,
0xd0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xb, 0xfc,
0x5, 0xff, 0x40, 0x0, 0x0, 0x0, 0x0, 0x2,
0xff, 0x70, 0xe, 0xfd, 0x10, 0x0, 0x0, 0x0,
0x0, 0xcf, 0xf1, 0x0, 0x4f, 0xfc, 0x20, 0x0,
0x0, 0x1, 0xbf, 0xf6, 0x0, 0x0, 0x7f, 0xff,
0xa4, 0x22, 0x48, 0xef, 0xf9, 0x0, 0x0, 0x0,
0x5f, 0xff, 0xff, 0xff, 0xff, 0xf6, 0x0, 0x0,
0x0, 0x0, 0x17, 0xce, 0xff, 0xfd, 0x71, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x1, 0xcf, 0xf7,
0x10, 0x4, 0xc3, 0x0, 0x0, 0x0, 0x0, 0x0,
0x9f, 0xff, 0xff, 0xff, 0x70, 0x0, 0x0, 0x0,
0x0, 0x0, 0x3a, 0xef, 0xea, 0x40,
/* U+0052 "R" */
0x7f, 0xff, 0xff, 0xff, 0xeb, 0x60, 0x0, 0x7,
0xff, 0xff, 0xff, 0xff, 0xff, 0xd2, 0x0, 0x7f,
0xe1, 0x11, 0x12, 0x49, 0xff, 0xe1, 0x7, 0xfe,
0x0, 0x0, 0x0, 0x3, 0xff, 0x90, 0x7f, 0xe0,
0x0, 0x0, 0x0, 0x9, 0xfe, 0x7, 0xfe, 0x0,
0x0, 0x0, 0x0, 0x5f, 0xf0, 0x7f, 0xe0, 0x0,
0x0, 0x0, 0x5, 0xff, 0x7, 0xfe, 0x0, 0x0,
0x0, 0x0, 0x9f, 0xe0, 0x7f, 0xe0, 0x0, 0x0,
0x0, 0x3f, 0xf8, 0x7, 0xfe, 0x11, 0x11, 0x13,
0x8f, 0xfe, 0x10, 0x7f, 0xff, 0xff, 0xff, 0xff,
0xfd, 0x20, 0x7, 0xff, 0xff, 0xff, 0xff, 0xfa,
0x0, 0x0, 0x7f, 0xe0, 0x0, 0x0, 0x7f, 0xf2,
0x0, 0x7, 0xfe, 0x0, 0x0, 0x0, 0xcf, 0xd0,
0x0, 0x7f, 0xe0, 0x0, 0x0, 0x1, 0xef, 0x90,
0x7, 0xfe, 0x0, 0x0, 0x0, 0x5, 0xff, 0x40,
0x7f, 0xe0, 0x0, 0x0, 0x0, 0x9, 0xfe, 0x10,
/* U+0053 "S" */
0x0, 0x0, 0x6b, 0xef, 0xfd, 0xa5, 0x0, 0x0,
0x2e, 0xff, 0xff, 0xff, 0xff, 0xd1, 0x0, 0xef,
0xe7, 0x21, 0x14, 0x8e, 0xc0, 0x6, 0xff, 0x20,
0x0, 0x0, 0x0, 0x20, 0x9, 0xfc, 0x0, 0x0,
0x0, 0x0, 0x0, 0x8, 0xfe, 0x0, 0x0, 0x0,
0x0, 0x0, 0x3, 0xff, 0xc3, 0x0, 0x0, 0x0,
0x0, 0x0, 0x7f, 0xff, 0xd9, 0x51, 0x0, 0x0,
0x0, 0x4, 0xbf, 0xff, 0xff, 0xc5, 0x0, 0x0,
0x0, 0x1, 0x59, 0xdf, 0xff, 0xb0, 0x0, 0x0,
0x0, 0x0, 0x2, 0xaf, 0xf7, 0x0, 0x0, 0x0,
0x0, 0x0, 0xb, 0xfc, 0x0, 0x0, 0x0, 0x0,
0x0, 0x7, 0xfe, 0x5, 0x80, 0x0, 0x0, 0x0,
0xc, 0xfb, 0xd, 0xfe, 0x84, 0x21, 0x25, 0xcf,
0xf4, 0x3, 0xdf, 0xff, 0xff, 0xff, 0xff, 0x60,
0x0, 0x4, 0x9d, 0xef, 0xec, 0x82, 0x0,
/* U+0054 "T" */
0xef, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xef,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x11, 0x11,
0x13, 0xff, 0x51, 0x11, 0x11, 0x0, 0x0, 0x2,
0xff, 0x30, 0x0, 0x0, 0x0, 0x0, 0x2, 0xff,
0x30, 0x0, 0x0, 0x0, 0x0, 0x2, 0xff, 0x30,
0x0, 0x0, 0x0, 0x0, 0x2, 0xff, 0x30, 0x0,
0x0, 0x0, 0x0, 0x2, 0xff, 0x30, 0x0, 0x0,
0x0, 0x0, 0x2, 0xff, 0x30, 0x0, 0x0, 0x0,
0x0, 0x2, 0xff, 0x30, 0x0, 0x0, 0x0, 0x0,
0x2, 0xff, 0x30, 0x0, 0x0, 0x0, 0x0, 0x2,
0xff, 0x30, 0x0, 0x0, 0x0, 0x0, 0x2, 0xff,
0x30, 0x0, 0x0, 0x0, 0x0, 0x2, 0xff, 0x30,
0x0, 0x0, 0x0, 0x0, 0x2, 0xff, 0x30, 0x0,
0x0, 0x0, 0x0, 0x2, 0xff, 0x30, 0x0, 0x0,
0x0, 0x0, 0x2, 0xff, 0x30, 0x0, 0x0,
/* U+0055 "U" */
0xaf, 0xc0, 0x0, 0x0, 0x0, 0x0, 0xcf, 0x9a,
0xfc, 0x0, 0x0, 0x0, 0x0, 0xc, 0xf9, 0xaf,
0xc0, 0x0, 0x0, 0x0, 0x0, 0xcf, 0x9a, 0xfc,
0x0, 0x0, 0x0, 0x0, 0xc, 0xf9, 0xaf, 0xc0,
0x0, 0x0, 0x0, 0x0, 0xcf, 0x9a, 0xfc, 0x0,
0x0, 0x0, 0x0, 0xc, 0xf9, 0xaf, 0xc0, 0x0,
0x0, 0x0, 0x0, 0xcf, 0x9a, 0xfc, 0x0, 0x0,
0x0, 0x0, 0xc, 0xf9, 0xaf, 0xc0, 0x0, 0x0,
0x0, 0x0, 0xcf, 0x99, 0xfc, 0x0, 0x0, 0x0,
0x0, 0xc, 0xf9, 0x9f, 0xd0, 0x0, 0x0, 0x0,
0x0, 0xdf, 0x87, 0xff, 0x0, 0x0, 0x0, 0x0,
0xf, 0xf6, 0x3f, 0xf5, 0x0, 0x0, 0x0, 0x5,
0xff, 0x20, 0xdf, 0xe1, 0x0, 0x0, 0x1, 0xef,
0xc0, 0x3, 0xff, 0xe7, 0x32, 0x38, 0xef, 0xf3,
0x0, 0x4, 0xff, 0xff, 0xff, 0xff, 0xe4, 0x0,
0x0, 0x1, 0x7c, 0xef, 0xec, 0x71, 0x0, 0x0,
/* U+0056 "V" */
0xd, 0xfc, 0x0, 0x0, 0x0, 0x0, 0x0, 0x8,
0xfe, 0x0, 0x6f, 0xf3, 0x0, 0x0, 0x0, 0x0,
0x0, 0xef, 0x70, 0x0, 0xef, 0xa0, 0x0, 0x0,
0x0, 0x0, 0x6f, 0xf1, 0x0, 0x8, 0xff, 0x10,
0x0, 0x0, 0x0, 0xc, 0xf9, 0x0, 0x0, 0x1f,
0xf8, 0x0, 0x0, 0x0, 0x4, 0xff, 0x20, 0x0,
0x0, 0xaf, 0xe0, 0x0, 0x0, 0x0, 0xbf, 0xb0,
0x0, 0x0, 0x3, 0xff, 0x50, 0x0, 0x0, 0x2f,
0xf4, 0x0, 0x0, 0x0, 0xc, 0xfc, 0x0, 0x0,
0x9, 0xfd, 0x0, 0x0, 0x0, 0x0, 0x5f, 0xf3,
0x0, 0x0, 0xff, 0x60, 0x0, 0x0, 0x0, 0x0,
0xef, 0xa0, 0x0, 0x7f, 0xf0, 0x0, 0x0, 0x0,
0x0, 0x7, 0xff, 0x10, 0xd, 0xf8, 0x0, 0x0,
0x0, 0x0, 0x0, 0x1f, 0xf8, 0x5, 0xff, 0x20,
0x0, 0x0, 0x0, 0x0, 0x0, 0x9f, 0xe0, 0xcf,
0xb0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x2, 0xff,
0x9f, 0xf4, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0xb, 0xff, 0xfd, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x4f, 0xff, 0x60, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0xdf, 0xe0, 0x0, 0x0,
0x0, 0x0,
/* U+0057 "W" */
0x1f, 0xf6, 0x0, 0x0, 0x0, 0x0, 0xaf, 0xe0,
0x0, 0x0, 0x0, 0x3, 0xff, 0x10, 0xbf, 0xb0,
0x0, 0x0, 0x0, 0xf, 0xff, 0x30, 0x0, 0x0,
0x0, 0x8f, 0xc0, 0x6, 0xff, 0x10, 0x0, 0x0,
0x5, 0xff, 0xf8, 0x0, 0x0, 0x0, 0xd, 0xf6,
0x0, 0x1f, 0xf6, 0x0, 0x0, 0x0, 0xbf, 0xef,
0xe0, 0x0, 0x0, 0x3, 0xff, 0x10, 0x0, 0xbf,
0xb0, 0x0, 0x0, 0x1f, 0xf4, 0xff, 0x30, 0x0,
0x0, 0x8f, 0xc0, 0x0, 0x6, 0xff, 0x10, 0x0,
0x6, 0xfd, 0xc, 0xf8, 0x0, 0x0, 0xd, 0xf6,
0x0, 0x0, 0x1f, 0xf5, 0x0, 0x0, 0xbf, 0x70,
0x6f, 0xe0, 0x0, 0x3, 0xff, 0x10, 0x0, 0x0,
0xcf, 0xb0, 0x0, 0x1f, 0xf2, 0x1, 0xff, 0x30,
0x0, 0x8f, 0xc0, 0x0, 0x0, 0x6, 0xff, 0x0,
0x6, 0xfd, 0x0, 0xc, 0xf8, 0x0, 0xd, 0xf7,
0x0, 0x0, 0x0, 0x1f, 0xf5, 0x0, 0xbf, 0x70,
0x0, 0x6f, 0xe0, 0x3, 0xff, 0x10, 0x0, 0x0,
0x0, 0xcf, 0xb0, 0x1f, 0xf2, 0x0, 0x1, 0xff,
0x30, 0x8f, 0xc0, 0x0, 0x0, 0x0, 0x6, 0xff,
0x6, 0xfc, 0x0, 0x0, 0xb, 0xf8, 0xd, 0xf7,
0x0, 0x0, 0x0, 0x0, 0x1f, 0xf5, 0xcf, 0x70,
0x0, 0x0, 0x6f, 0xe3, 0xff, 0x20, 0x0, 0x0,
0x0, 0x0, 0xcf, 0xcf, 0xf2, 0x0, 0x0, 0x1,
0xff, 0xbf, 0xc0, 0x0, 0x0, 0x0, 0x0, 0x7,
0xff, 0xfc, 0x0, 0x0, 0x0, 0xb, 0xff, 0xf7,
0x0, 0x0, 0x0, 0x0, 0x0, 0x1f, 0xff, 0x70,
0x0, 0x0, 0x0, 0x6f, 0xff, 0x20, 0x0, 0x0,
0x0, 0x0, 0x0, 0xcf, 0xf1, 0x0, 0x0, 0x0,
0x1, 0xff, 0xc0, 0x0, 0x0, 0x0,
/* U+0058 "X" */
0xe, 0xfc, 0x0, 0x0, 0x0, 0x0, 0x8f, 0xe1,
0x3, 0xff, 0x80, 0x0, 0x0, 0x4, 0xff, 0x50,
0x0, 0x8f, 0xf3, 0x0, 0x0, 0x1e, 0xf9, 0x0,
0x0, 0xc, 0xfe, 0x10, 0x0, 0xbf, 0xd0, 0x0,
0x0, 0x2, 0xff, 0xa0, 0x6, 0xff, 0x20, 0x0,
0x0, 0x0, 0x5f, 0xf6, 0x2f, 0xf6, 0x0, 0x0,
0x0, 0x0, 0xa, 0xff, 0xdf, 0xb0, 0x0, 0x0,
0x0, 0x0, 0x0, 0xef, 0xfe, 0x10, 0x0, 0x0,
0x0, 0x0, 0x0, 0x9f, 0xfb, 0x0, 0x0, 0x0,
0x0, 0x0, 0x4, 0xff, 0xff, 0x60, 0x0, 0x0,
0x0, 0x0, 0x1e, 0xfa, 0x9f, 0xf2, 0x0, 0x0,
0x0, 0x0, 0xbf, 0xe1, 0xd, 0xfd, 0x0, 0x0,
0x0, 0x6, 0xff, 0x40, 0x2, 0xff, 0x90, 0x0,
0x0, 0x2f, 0xf8, 0x0, 0x0, 0x6f, 0xf4, 0x0,
0x0, 0xdf, 0xd0, 0x0, 0x0, 0xb, 0xfe, 0x10,
0x9, 0xff, 0x20, 0x0, 0x0, 0x1, 0xef, 0xb0,
0x5f, 0xf6, 0x0, 0x0, 0x0, 0x0, 0x4f, 0xf7,
/* U+0059 "Y" */
0xc, 0xfc, 0x0, 0x0, 0x0, 0x0, 0x1, 0xff,
0x50, 0x3f, 0xf5, 0x0, 0x0, 0x0, 0x0, 0xaf,
0xb0, 0x0, 0x9f, 0xe0, 0x0, 0x0, 0x0, 0x4f,
0xf2, 0x0, 0x1, 0xef, 0x90, 0x0, 0x0, 0xd,
0xf8, 0x0, 0x0, 0x6, 0xff, 0x20, 0x0, 0x7,
0xfe, 0x0, 0x0, 0x0, 0xc, 0xfc, 0x0, 0x1,
0xff, 0x50, 0x0, 0x0, 0x0, 0x3f, 0xf5, 0x0,
0xaf, 0xb0, 0x0, 0x0, 0x0, 0x0, 0x9f, 0xe0,
0x4f, 0xf2, 0x0, 0x0, 0x0, 0x0, 0x1, 0xef,
0x9d, 0xf8, 0x0, 0x0, 0x0, 0x0, 0x0, 0x6,
0xff, 0xfe, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0xc, 0xff, 0x50, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x6f, 0xf0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x6, 0xff, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x6f, 0xf0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x6, 0xff, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x6f, 0xf0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x6, 0xff, 0x0, 0x0, 0x0,
0x0,
/* U+005A "Z" */
0xcf, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfc, 0xc,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xb0, 0x11,
0x11, 0x11, 0x11, 0x11, 0xcf, 0xf2, 0x0, 0x0,
0x0, 0x0, 0x0, 0x8f, 0xf4, 0x0, 0x0, 0x0,
0x0, 0x0, 0x5f, 0xf8, 0x0, 0x0, 0x0, 0x0,
0x0, 0x2f, 0xfb, 0x0, 0x0, 0x0, 0x0, 0x0,
0xd, 0xfd, 0x0, 0x0, 0x0, 0x0, 0x0, 0xb,
0xff, 0x20, 0x0, 0x0, 0x0, 0x0, 0x8, 0xff,
0x50, 0x0, 0x0, 0x0, 0x0, 0x4, 0xff, 0x80,
0x0, 0x0, 0x0, 0x0, 0x2, 0xff, 0xb0, 0x0,
0x0, 0x0, 0x0, 0x0, 0xdf, 0xd1, 0x0, 0x0,
0x0, 0x0, 0x0, 0xbf, 0xf2, 0x0, 0x0, 0x0,
0x0, 0x0, 0x8f, 0xf5, 0x0, 0x0, 0x0, 0x0,
0x0, 0x4f, 0xfa, 0x11, 0x11, 0x11, 0x11, 0x11,
0xe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xf1,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x10,
/* U+0061 "a" */
0x0, 0x6b, 0xef, 0xfd, 0x81, 0x0, 0x2e, 0xff,
0xff, 0xff, 0xfe, 0x10, 0xe, 0xb5, 0x10, 0x27,
0xff, 0xb0, 0x1, 0x0, 0x0, 0x0, 0x6f, 0xf0,
0x0, 0x0, 0x0, 0x0, 0x1f, 0xf3, 0x0, 0x37,
0xaa, 0xaa, 0xaf, 0xf4, 0xa, 0xff, 0xff, 0xff,
0xff, 0xf4, 0x6f, 0xf6, 0x10, 0x0, 0xf, 0xf4,
0xbf, 0x90, 0x0, 0x0, 0xf, 0xf4, 0xcf, 0x80,
0x0, 0x0, 0x5f, 0xf4, 0x8f, 0xe2, 0x0, 0x4,
0xff, 0xf4, 0x1d, 0xff, 0xcb, 0xdf, 0xdf, 0xf4,
0x1, 0x8d, 0xff, 0xd8, 0xe, 0xf4,
/* U+0062 "b" */
0xdf, 0x70, 0x0, 0x0, 0x0, 0x0, 0x0, 0xdf,
0x70, 0x0, 0x0, 0x0, 0x0, 0x0, 0xdf, 0x70,
0x0, 0x0, 0x0, 0x0, 0x0, 0xdf, 0x70, 0x0,
0x0, 0x0, 0x0, 0x0, 0xdf, 0x70, 0x0, 0x0,
0x0, 0x0, 0x0, 0xdf, 0x70, 0x7c, 0xfe, 0xc7,
0x10, 0x0, 0xdf, 0x9d, 0xff, 0xff, 0xff, 0xe3,
0x0, 0xdf, 0xff, 0xa3, 0x12, 0x6e, 0xfe, 0x20,
0xdf, 0xf8, 0x0, 0x0, 0x1, 0xef, 0xa0, 0xdf,
0xe0, 0x0, 0x0, 0x0, 0x6f, 0xf1, 0xdf, 0x90,
0x0, 0x0, 0x0, 0x1f, 0xf3, 0xdf, 0x70, 0x0,
0x0, 0x0, 0xf, 0xf5, 0xdf, 0x90, 0x0, 0x0,
0x0, 0x1f, 0xf3, 0xdf, 0xe0, 0x0, 0x0, 0x0,
0x6f, 0xf1, 0xdf, 0xf8, 0x0, 0x0, 0x2, 0xef,
0xa0, 0xdf, 0xff, 0xa3, 0x12, 0x6e, 0xff, 0x20,
0xdf, 0x8d, 0xff, 0xff, 0xff, 0xe3, 0x0, 0xdf,
0x60, 0x7d, 0xfe, 0xc7, 0x10, 0x0,
/* U+0063 "c" */
0x0, 0x3, 0xad, 0xfe, 0xc6, 0x0, 0x0, 0x9f,
0xff, 0xff, 0xff, 0xc1, 0x9, 0xff, 0x93, 0x12,
0x7f, 0xfa, 0x4f, 0xf6, 0x0, 0x0, 0x3, 0x91,
0xaf, 0xc0, 0x0, 0x0, 0x0, 0x0, 0xdf, 0x70,
0x0, 0x0, 0x0, 0x0, 0xff, 0x50, 0x0, 0x0,
0x0, 0x0, 0xdf, 0x70, 0x0, 0x0, 0x0, 0x0,
0xaf, 0xc0, 0x0, 0x0, 0x0, 0x0, 0x4f, 0xf6,
0x0, 0x0, 0x2, 0x91, 0x9, 0xff, 0x93, 0x12,
0x7f, 0xfa, 0x0, 0x9f, 0xff, 0xff, 0xff, 0xc1,
0x0, 0x3, 0xad, 0xfe, 0xc6, 0x0,
/* U+0064 "d" */
0x0, 0x0, 0x0, 0x0, 0x0, 0x2f, 0xf3, 0x0,
0x0, 0x0, 0x0, 0x0, 0x2f, 0xf3, 0x0, 0x0,
0x0, 0x0, 0x0, 0x2f, 0xf3, 0x0, 0x0, 0x0,
0x0, 0x0, 0x2f, 0xf3, 0x0, 0x0, 0x0, 0x0,
0x0, 0x2f, 0xf3, 0x0, 0x5, 0xbe, 0xfe, 0x92,
0x2f, 0xf3, 0x1, 0xbf, 0xff, 0xff, 0xff, 0x7f,
0xf3, 0xb, 0xff, 0x93, 0x12, 0x7f, 0xff, 0xf3,
0x5f, 0xf6, 0x0, 0x0, 0x3, 0xff, 0xf3, 0xbf,
0xc0, 0x0, 0x0, 0x0, 0x8f, 0xf3, 0xdf, 0x70,
0x0, 0x0, 0x0, 0x3f, 0xf3, 0xff, 0x50, 0x0,
0x0, 0x0, 0x1f, 0xf3, 0xdf, 0x70, 0x0, 0x0,
0x0, 0x3f, 0xf3, 0xbf, 0xb0, 0x0, 0x0, 0x0,
0x7f, 0xf3, 0x5f, 0xf5, 0x0, 0x0, 0x2, 0xff,
0xf3, 0xb, 0xff, 0x71, 0x0, 0x5e, 0xff, 0xf3,
0x1, 0xbf, 0xff, 0xef, 0xff, 0x7f, 0xf3, 0x0,
0x5, 0xbe, 0xfe, 0xa3, 0xf, 0xf3,
/* U+0065 "e" */
0x0, 0x5, 0xbe, 0xfd, 0xa3, 0x0, 0x0, 0xa,
0xff, 0xff, 0xff, 0xf8, 0x0, 0xa, 0xfe, 0x61,
0x2, 0x8f, 0xf7, 0x4, 0xff, 0x20, 0x0, 0x0,
0x5f, 0xf1, 0xaf, 0x90, 0x0, 0x0, 0x0, 0xcf,
0x6d, 0xfc, 0xbb, 0xbb, 0xbb, 0xbd, 0xf9, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xad, 0xf6, 0x0,
0x0, 0x0, 0x0, 0x0, 0xaf, 0xc0, 0x0, 0x0,
0x0, 0x0, 0x4, 0xff, 0x60, 0x0, 0x0, 0x6,
0x0, 0xa, 0xff, 0xa3, 0x11, 0x4b, 0xf8, 0x0,
0x9, 0xff, 0xff, 0xff, 0xff, 0x40, 0x0, 0x3,
0xad, 0xff, 0xd8, 0x10, 0x0,
/* U+0066 "f" */
0x0, 0x0, 0x8d, 0xfe, 0xa1, 0x0, 0xb, 0xff,
0xff, 0xf0, 0x0, 0x4f, 0xf5, 0x0, 0x30, 0x0,
0x7f, 0xd0, 0x0, 0x0, 0x0, 0x7f, 0xc0, 0x0,
0x0, 0xaf, 0xff, 0xff, 0xff, 0x70, 0x9e, 0xff,
0xfe, 0xee, 0x60, 0x0, 0x7f, 0xd0, 0x0, 0x0,
0x0, 0x7f, 0xd0, 0x0, 0x0, 0x0, 0x7f, 0xd0,
0x0, 0x0, 0x0, 0x7f, 0xd0, 0x0, 0x0, 0x0,
0x7f, 0xd0, 0x0, 0x0, 0x0, 0x7f, 0xd0, 0x0,
0x0, 0x0, 0x7f, 0xd0, 0x0, 0x0, 0x0, 0x7f,
0xd0, 0x0, 0x0, 0x0, 0x7f, 0xd0, 0x0, 0x0,
0x0, 0x7f, 0xd0, 0x0, 0x0, 0x0, 0x7f, 0xd0,
0x0, 0x0,
/* U+0067 "g" */
0x0, 0x5, 0xbe, 0xfe, 0xa3, 0xd, 0xf5, 0x0,
0xbf, 0xff, 0xff, 0xff, 0x8d, 0xf5, 0xb, 0xff,
0x93, 0x12, 0x6e, 0xff, 0xf5, 0x4f, 0xf6, 0x0,
0x0, 0x1, 0xef, 0xf5, 0xbf, 0xc0, 0x0, 0x0,
0x0, 0x5f, 0xf5, 0xdf, 0x70, 0x0, 0x0, 0x0,
0xf, 0xf5, 0xff, 0x50, 0x0, 0x0, 0x0, 0xe,
0xf5, 0xdf, 0x70, 0x0, 0x0, 0x0, 0xf, 0xf5,
0xaf, 0xc0, 0x0, 0x0, 0x0, 0x5f, 0xf5, 0x4f,
0xf6, 0x0, 0x0, 0x1, 0xef, 0xf5, 0xa, 0xff,
0xa3, 0x12, 0x6e, 0xff, 0xf5, 0x0, 0xbf, 0xff,
0xff, 0xff, 0x8f, 0xf5, 0x0, 0x5, 0xbe, 0xfe,
0xa3, 0xf, 0xf4, 0x0, 0x0, 0x0, 0x0, 0x0,
0x2f, 0xf1, 0x3, 0x10, 0x0, 0x0, 0x0, 0xaf,
0xd0, 0xd, 0xf9, 0x52, 0x11, 0x4b, 0xff, 0x50,
0xa, 0xff, 0xff, 0xff, 0xff, 0xf7, 0x0, 0x0,
0x28, 0xce, 0xff, 0xd9, 0x30, 0x0,
/* U+0068 "h" */
0xdf, 0x70, 0x0, 0x0, 0x0, 0x0, 0xd, 0xf7,
0x0, 0x0, 0x0, 0x0, 0x0, 0xdf, 0x70, 0x0,
0x0, 0x0, 0x0, 0xd, 0xf7, 0x0, 0x0, 0x0,
0x0, 0x0, 0xdf, 0x70, 0x0, 0x0, 0x0, 0x0,
0xd, 0xf7, 0x18, 0xdf, 0xfc, 0x70, 0x0, 0xdf,
0xae, 0xff, 0xff, 0xff, 0xc0, 0xd, 0xff, 0xf8,
0x31, 0x4a, 0xff, 0x90, 0xdf, 0xf5, 0x0, 0x0,
0xa, 0xff, 0xd, 0xfc, 0x0, 0x0, 0x0, 0x3f,
0xf2, 0xdf, 0x80, 0x0, 0x0, 0x1, 0xff, 0x3d,
0xf7, 0x0, 0x0, 0x0, 0xf, 0xf4, 0xdf, 0x70,
0x0, 0x0, 0x0, 0xff, 0x4d, 0xf7, 0x0, 0x0,
0x0, 0xf, 0xf4, 0xdf, 0x70, 0x0, 0x0, 0x0,
0xff, 0x4d, 0xf7, 0x0, 0x0, 0x0, 0xf, 0xf4,
0xdf, 0x70, 0x0, 0x0, 0x0, 0xff, 0x4d, 0xf7,
0x0, 0x0, 0x0, 0xf, 0xf4,
/* U+0069 "i" */
0xb, 0xf6, 0x2f, 0xfd, 0xb, 0xf7, 0x0, 0x0,
0x0, 0x0, 0xd, 0xf7, 0xd, 0xf7, 0xd, 0xf7,
0xd, 0xf7, 0xd, 0xf7, 0xd, 0xf7, 0xd, 0xf7,
0xd, 0xf7, 0xd, 0xf7, 0xd, 0xf7, 0xd, 0xf7,
0xd, 0xf7, 0xd, 0xf7,
/* U+006A "j" */
0x0, 0x0, 0x9, 0xf8, 0x0, 0x0, 0x1, 0xff,
0xf0, 0x0, 0x0, 0xa, 0xf8, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0xbf, 0x90, 0x0, 0x0, 0xb, 0xf9, 0x0,
0x0, 0x0, 0xbf, 0x90, 0x0, 0x0, 0xb, 0xf9,
0x0, 0x0, 0x0, 0xbf, 0x90, 0x0, 0x0, 0xb,
0xf9, 0x0, 0x0, 0x0, 0xbf, 0x90, 0x0, 0x0,
0xb, 0xf9, 0x0, 0x0, 0x0, 0xbf, 0x90, 0x0,
0x0, 0xb, 0xf9, 0x0, 0x0, 0x0, 0xbf, 0x90,
0x0, 0x0, 0xb, 0xf9, 0x0, 0x0, 0x0, 0xbf,
0x90, 0x0, 0x0, 0xb, 0xf9, 0x0, 0x0, 0x0,
0xdf, 0x80, 0x4, 0x20, 0x5f, 0xf4, 0x0, 0xef,
0xff, 0xfc, 0x0, 0x9, 0xef, 0xe9, 0x0, 0x0,
/* U+006B "k" */
0xdf, 0x70, 0x0, 0x0, 0x0, 0x0, 0xd, 0xf7,
0x0, 0x0, 0x0, 0x0, 0x0, 0xdf, 0x70, 0x0,
0x0, 0x0, 0x0, 0xd, 0xf7, 0x0, 0x0, 0x0,
0x0, 0x0, 0xdf, 0x70, 0x0, 0x0, 0x0, 0x0,
0xd, 0xf7, 0x0, 0x0, 0x3, 0xef, 0xa0, 0xdf,
0x70, 0x0, 0x3, 0xff, 0xb0, 0xd, 0xf7, 0x0,
0x4, 0xff, 0xb0, 0x0, 0xdf, 0x70, 0x5, 0xff,
0xb0, 0x0, 0xd, 0xf7, 0x6, 0xff, 0xb0, 0x0,
0x0, 0xdf, 0x77, 0xff, 0xf1, 0x0, 0x0, 0xd,
0xfe, 0xff, 0xff, 0xb0, 0x0, 0x0, 0xdf, 0xff,
0x87, 0xff, 0x70, 0x0, 0xd, 0xff, 0x70, 0xa,
0xff, 0x40, 0x0, 0xdf, 0x90, 0x0, 0xd, 0xfe,
0x10, 0xd, 0xf7, 0x0, 0x0, 0x2e, 0xfc, 0x0,
0xdf, 0x70, 0x0, 0x0, 0x4f, 0xf9, 0xd, 0xf7,
0x0, 0x0, 0x0, 0x7f, 0xf5,
/* U+006C "l" */
0xdf, 0x7d, 0xf7, 0xdf, 0x7d, 0xf7, 0xdf, 0x7d,
0xf7, 0xdf, 0x7d, 0xf7, 0xdf, 0x7d, 0xf7, 0xdf,
0x7d, 0xf7, 0xdf, 0x7d, 0xf7, 0xdf, 0x7d, 0xf7,
0xdf, 0x7d, 0xf7,
/* U+006D "m" */
0xdf, 0x61, 0x9d, 0xfe, 0xb5, 0x0, 0x7, 0xcf,
0xfd, 0x80, 0x0, 0xdf, 0xaf, 0xff, 0xff, 0xff,
0x92, 0xef, 0xff, 0xff, 0xfd, 0x10, 0xdf, 0xfe,
0x60, 0x3, 0xcf, 0xff, 0xfa, 0x20, 0x17, 0xff,
0xa0, 0xdf, 0xf3, 0x0, 0x0, 0xe, 0xff, 0xa0,
0x0, 0x0, 0x8f, 0xf0, 0xdf, 0xc0, 0x0, 0x0,
0x9, 0xff, 0x20, 0x0, 0x0, 0x2f, 0xf3, 0xdf,
0x80, 0x0, 0x0, 0x7, 0xff, 0x0, 0x0, 0x0,
0xf, 0xf4, 0xdf, 0x70, 0x0, 0x0, 0x6, 0xfe,
0x0, 0x0, 0x0, 0xf, 0xf4, 0xdf, 0x70, 0x0,
0x0, 0x6, 0xfe, 0x0, 0x0, 0x0, 0xf, 0xf4,
0xdf, 0x70, 0x0, 0x0, 0x6, 0xfe, 0x0, 0x0,
0x0, 0xf, 0xf4, 0xdf, 0x70, 0x0, 0x0, 0x6,
0xfe, 0x0, 0x0, 0x0, 0xf, 0xf4, 0xdf, 0x70,
0x0, 0x0, 0x6, 0xfe, 0x0, 0x0, 0x0, 0xf,
0xf4, 0xdf, 0x70, 0x0, 0x0, 0x6, 0xfe, 0x0,
0x0, 0x0, 0xf, 0xf4, 0xdf, 0x70, 0x0, 0x0,
0x6, 0xfe, 0x0, 0x0, 0x0, 0xf, 0xf4,
/* U+006E "n" */
0xdf, 0x61, 0x8d, 0xff, 0xc7, 0x0, 0xd, 0xf9,
0xff, 0xff, 0xff, 0xfc, 0x0, 0xdf, 0xff, 0x61,
0x2, 0x8f, 0xf9, 0xd, 0xff, 0x40, 0x0, 0x0,
0x9f, 0xf0, 0xdf, 0xc0, 0x0, 0x0, 0x3, 0xff,
0x2d, 0xf8, 0x0, 0x0, 0x0, 0x1f, 0xf3, 0xdf,
0x70, 0x0, 0x0, 0x0, 0xff, 0x4d, 0xf7, 0x0,
0x0, 0x0, 0xf, 0xf4, 0xdf, 0x70, 0x0, 0x0,
0x0, 0xff, 0x4d, 0xf7, 0x0, 0x0, 0x0, 0xf,
0xf4, 0xdf, 0x70, 0x0, 0x0, 0x0, 0xff, 0x4d,
0xf7, 0x0, 0x0, 0x0, 0xf, 0xf4, 0xdf, 0x70,
0x0, 0x0, 0x0, 0xff, 0x40,
/* U+006F "o" */
0x0, 0x4, 0xad, 0xfe, 0xb5, 0x0, 0x0, 0x0,
0xaf, 0xff, 0xff, 0xff, 0xc1, 0x0, 0xa, 0xff,
0x93, 0x12, 0x7f, 0xfd, 0x0, 0x4f, 0xf6, 0x0,
0x0, 0x3, 0xff, 0x80, 0xaf, 0xc0, 0x0, 0x0,
0x0, 0x8f, 0xe0, 0xdf, 0x70, 0x0, 0x0, 0x0,
0x3f, 0xf1, 0xff, 0x50, 0x0, 0x0, 0x0, 0x1f,
0xf3, 0xdf, 0x70, 0x0, 0x0, 0x0, 0x3f, 0xf1,
0xaf, 0xc0, 0x0, 0x0, 0x0, 0x8f, 0xe0, 0x4f,
0xf6, 0x0, 0x0, 0x3, 0xff, 0x80, 0xa, 0xff,
0x93, 0x12, 0x7f, 0xfd, 0x0, 0x0, 0x9f, 0xff,
0xff, 0xff, 0xc1, 0x0, 0x0, 0x4, 0xad, 0xfe,
0xb5, 0x0, 0x0,
/* U+0070 "p" */
0xdf, 0x61, 0x8d, 0xfe, 0xc7, 0x10, 0x0, 0xdf,
0x8e, 0xff, 0xff, 0xff, 0xe3, 0x0, 0xdf, 0xff,
0x92, 0x0, 0x5d, 0xfe, 0x20, 0xdf, 0xf7, 0x0,
0x0, 0x1, 0xef, 0xa0, 0xdf, 0xd0, 0x0, 0x0,
0x0, 0x5f, 0xf1, 0xdf, 0x90, 0x0, 0x0, 0x0,
0x1f, 0xf3, 0xdf, 0x70, 0x0, 0x0, 0x0, 0xf,
0xf5, 0xdf, 0x90, 0x0, 0x0, 0x0, 0x1f, 0xf3,
0xdf, 0xe0, 0x0, 0x0, 0x0, 0x6f, 0xf1, 0xdf,
0xf8, 0x0, 0x0, 0x2, 0xef, 0xa0, 0xdf, 0xff,
0xa3, 0x12, 0x6e, 0xff, 0x20, 0xdf, 0x9d, 0xff,
0xff, 0xff, 0xe3, 0x0, 0xdf, 0x70, 0x7c, 0xfe,
0xc7, 0x10, 0x0, 0xdf, 0x70, 0x0, 0x0, 0x0,
0x0, 0x0, 0xdf, 0x70, 0x0, 0x0, 0x0, 0x0,
0x0, 0xdf, 0x70, 0x0, 0x0, 0x0, 0x0, 0x0,
0xdf, 0x70, 0x0, 0x0, 0x0, 0x0, 0x0, 0xdf,
0x70, 0x0, 0x0, 0x0, 0x0, 0x0,
/* U+0071 "q" */
0x0, 0x5, 0xbe, 0xfe, 0xa2, 0xf, 0xf3, 0x1,
0xbf, 0xff, 0xff, 0xff, 0x6f, 0xf3, 0xb, 0xff,
0x93, 0x12, 0x7f, 0xff, 0xf3, 0x5f, 0xf6, 0x0,
0x0, 0x3, 0xff, 0xf3, 0xbf, 0xc0, 0x0, 0x0,
0x0, 0x8f, 0xf3, 0xdf, 0x70, 0x0, 0x0, 0x0,
0x3f, 0xf3, 0xff, 0x50, 0x0, 0x0, 0x0, 0x1f,
0xf3, 0xdf, 0x70, 0x0, 0x0, 0x0, 0x3f, 0xf3,
0xbf, 0xc0, 0x0, 0x0, 0x0, 0x8f, 0xf3, 0x5f,
0xf6, 0x0, 0x0, 0x3, 0xff, 0xf3, 0xb, 0xff,
0x93, 0x12, 0x7f, 0xff, 0xf3, 0x1, 0xbf, 0xff,
0xff, 0xff, 0x7f, 0xf3, 0x0, 0x5, 0xbe, 0xfe,
0x92, 0x2f, 0xf3, 0x0, 0x0, 0x0, 0x0, 0x0,
0x2f, 0xf3, 0x0, 0x0, 0x0, 0x0, 0x0, 0x2f,
0xf3, 0x0, 0x0, 0x0, 0x0, 0x0, 0x2f, 0xf3,
0x0, 0x0, 0x0, 0x0, 0x0, 0x2f, 0xf3, 0x0,
0x0, 0x0, 0x0, 0x0, 0x2f, 0xf3,
/* U+0072 "r" */
0xdf, 0x61, 0x8d, 0xf0, 0xdf, 0x7e, 0xff, 0xf0,
0xdf, 0xff, 0xb5, 0x40, 0xdf, 0xf7, 0x0, 0x0,
0xdf, 0xd0, 0x0, 0x0, 0xdf, 0x90, 0x0, 0x0,
0xdf, 0x70, 0x0, 0x0, 0xdf, 0x70, 0x0, 0x0,
0xdf, 0x70, 0x0, 0x0, 0xdf, 0x70, 0x0, 0x0,
0xdf, 0x70, 0x0, 0x0, 0xdf, 0x70, 0x0, 0x0,
0xdf, 0x70, 0x0, 0x0,
/* U+0073 "s" */
0x0, 0x18, 0xcf, 0xfe, 0xb7, 0x10, 0x2, 0xef,
0xff, 0xff, 0xff, 0xb0, 0xb, 0xfe, 0x41, 0x2,
0x6c, 0x30, 0xf, 0xf5, 0x0, 0x0, 0x0, 0x0,
0xe, 0xf9, 0x0, 0x0, 0x0, 0x0, 0x8, 0xff,
0xd9, 0x52, 0x0, 0x0, 0x0, 0x8f, 0xff, 0xff,
0xe9, 0x10, 0x0, 0x0, 0x47, 0xad, 0xff, 0xc0,
0x0, 0x0, 0x0, 0x0, 0x5f, 0xf3, 0x1, 0x0,
0x0, 0x0, 0xf, 0xf4, 0xe, 0xc6, 0x20, 0x3,
0xaf, 0xf1, 0x3f, 0xff, 0xff, 0xff, 0xff, 0x60,
0x1, 0x7b, 0xef, 0xfd, 0x92, 0x0,
/* U+0074 "t" */
0x0, 0x7f, 0xd0, 0x0, 0x0, 0x0, 0x7f, 0xd0,
0x0, 0x0, 0x0, 0x7f, 0xd0, 0x0, 0x0, 0xaf,
0xff, 0xff, 0xff, 0x70, 0x9e, 0xff, 0xfe, 0xee,
0x60, 0x0, 0x7f, 0xd0, 0x0, 0x0, 0x0, 0x7f,
0xd0, 0x0, 0x0, 0x0, 0x7f, 0xd0, 0x0, 0x0,
0x0, 0x7f, 0xd0, 0x0, 0x0, 0x0, 0x7f, 0xd0,
0x0, 0x0, 0x0, 0x7f, 0xd0, 0x0, 0x0, 0x0,
0x7f, 0xd0, 0x0, 0x0, 0x0, 0x7f, 0xe0, 0x0,
0x0, 0x0, 0x4f, 0xf7, 0x1, 0x50, 0x0, 0xc,
0xff, 0xff, 0xf1, 0x0, 0x0, 0x9e, 0xfd, 0x81,
/* U+0075 "u" */
0xff, 0x60, 0x0, 0x0, 0x4, 0xff, 0xf, 0xf6,
0x0, 0x0, 0x0, 0x4f, 0xf0, 0xff, 0x60, 0x0,
0x0, 0x4, 0xff, 0xf, 0xf6, 0x0, 0x0, 0x0,
0x4f, 0xf0, 0xff, 0x60, 0x0, 0x0, 0x4, 0xff,
0xf, 0xf6, 0x0, 0x0, 0x0, 0x4f, 0xf0, 0xff,
0x60, 0x0, 0x0, 0x4, 0xff, 0xe, 0xf6, 0x0,
0x0, 0x0, 0x5f, 0xf0, 0xdf, 0x80, 0x0, 0x0,
0x8, 0xff, 0xa, 0xfe, 0x0, 0x0, 0x1, 0xef,
0xf0, 0x3f, 0xfb, 0x20, 0x4, 0xdf, 0xff, 0x0,
0x8f, 0xff, 0xff, 0xff, 0x9f, 0xf0, 0x0, 0x4b,
0xef, 0xea, 0x32, 0xff, 0x0,
/* U+0076 "v" */
0xd, 0xf9, 0x0, 0x0, 0x0, 0x1, 0xff, 0x30,
0x6f, 0xf0, 0x0, 0x0, 0x0, 0x7f, 0xc0, 0x0,
0xef, 0x60, 0x0, 0x0, 0xd, 0xf5, 0x0, 0x8,
0xfd, 0x0, 0x0, 0x5, 0xfe, 0x0, 0x0, 0x2f,
0xf3, 0x0, 0x0, 0xbf, 0x80, 0x0, 0x0, 0xbf,
0xa0, 0x0, 0x2f, 0xf1, 0x0, 0x0, 0x4, 0xff,
0x10, 0x9, 0xfa, 0x0, 0x0, 0x0, 0xd, 0xf7,
0x1, 0xff, 0x30, 0x0, 0x0, 0x0, 0x6f, 0xe0,
0x7f, 0xc0, 0x0, 0x0, 0x0, 0x0, 0xff, 0x5d,
0xf5, 0x0, 0x0, 0x0, 0x0, 0x8, 0xfe, 0xfe,
0x0, 0x0, 0x0, 0x0, 0x0, 0x2f, 0xff, 0x80,
0x0, 0x0, 0x0, 0x0, 0x0, 0xbf, 0xf1, 0x0,
0x0, 0x0,
/* U+0077 "w" */
0xaf, 0x80, 0x0, 0x0, 0x5, 0xff, 0x0, 0x0,
0x0, 0xc, 0xf4, 0x5f, 0xd0, 0x0, 0x0, 0xb,
0xff, 0x50, 0x0, 0x0, 0x2f, 0xe0, 0xe, 0xf3,
0x0, 0x0, 0x1f, 0xff, 0xb0, 0x0, 0x0, 0x8f,
0x80, 0x9, 0xf9, 0x0, 0x0, 0x7f, 0xbf, 0xf1,
0x0, 0x0, 0xef, 0x20, 0x3, 0xfe, 0x0, 0x0,
0xcf, 0x4b, 0xf7, 0x0, 0x4, 0xfc, 0x0, 0x0,
0xdf, 0x40, 0x2, 0xfe, 0x5, 0xfc, 0x0, 0xa,
0xf6, 0x0, 0x0, 0x7f, 0xa0, 0x8, 0xf8, 0x0,
0xef, 0x20, 0xf, 0xf1, 0x0, 0x0, 0x2f, 0xf0,
0xe, 0xf2, 0x0, 0x9f, 0x80, 0x5f, 0xb0, 0x0,
0x0, 0xc, 0xf5, 0x4f, 0xc0, 0x0, 0x3f, 0xe0,
0xbf, 0x50, 0x0, 0x0, 0x6, 0xfb, 0xaf, 0x60,
0x0, 0xd, 0xf5, 0xfe, 0x0, 0x0, 0x0, 0x1,
0xff, 0xff, 0x0, 0x0, 0x7, 0xff, 0xf9, 0x0,
0x0, 0x0, 0x0, 0xaf, 0xfa, 0x0, 0x0, 0x1,
0xff, 0xf3, 0x0, 0x0, 0x0, 0x0, 0x4f, 0xf4,
0x0, 0x0, 0x0, 0xbf, 0xd0, 0x0, 0x0,
/* U+0078 "x" */
0x1e, 0xf8, 0x0, 0x0, 0x4, 0xff, 0x40, 0x4f,
0xf4, 0x0, 0x1, 0xef, 0x80, 0x0, 0x8f, 0xe1,
0x0, 0xbf, 0xb0, 0x0, 0x0, 0xcf, 0xb0, 0x7f,
0xe1, 0x0, 0x0, 0x1, 0xef, 0xaf, 0xf4, 0x0,
0x0, 0x0, 0x4, 0xff, 0xf7, 0x0, 0x0, 0x0,
0x0, 0xd, 0xff, 0x10, 0x0, 0x0, 0x0, 0x8,
0xff, 0xfb, 0x0, 0x0, 0x0, 0x4, 0xff, 0x5e,
0xf7, 0x0, 0x0, 0x1, 0xef, 0x80, 0x4f, 0xf3,
0x0, 0x0, 0xcf, 0xc0, 0x0, 0x8f, 0xe1, 0x0,
0x8f, 0xe1, 0x0, 0x0, 0xcf, 0xb0, 0x4f, 0xf4,
0x0, 0x0, 0x2, 0xff, 0x80,
/* U+0079 "y" */
0xd, 0xf9, 0x0, 0x0, 0x0, 0x1, 0xff, 0x30,
0x6f, 0xf0, 0x0, 0x0, 0x0, 0x7f, 0xc0, 0x0,
0xef, 0x60, 0x0, 0x0, 0xd, 0xf5, 0x0, 0x8,
0xfd, 0x0, 0x0, 0x4, 0xfe, 0x0, 0x0, 0x2f,
0xf4, 0x0, 0x0, 0xbf, 0x80, 0x0, 0x0, 0xbf,
0xb0, 0x0, 0x2f, 0xf1, 0x0, 0x0, 0x4, 0xff,
0x10, 0x8, 0xfa, 0x0, 0x0, 0x0, 0xd, 0xf8,
0x0, 0xef, 0x30, 0x0, 0x0, 0x0, 0x6f, 0xe0,
0x6f, 0xc0, 0x0, 0x0, 0x0, 0x0, 0xef, 0x6c,
0xf5, 0x0, 0x0, 0x0, 0x0, 0x8, 0xfe, 0xfe,
0x0, 0x0, 0x0, 0x0, 0x0, 0x1f, 0xff, 0x70,
0x0, 0x0, 0x0, 0x0, 0x0, 0xaf, 0xf1, 0x0,
0x0, 0x0, 0x0, 0x0, 0xa, 0xfa, 0x0, 0x0,
0x0, 0x0, 0x0, 0x2, 0xff, 0x30, 0x0, 0x0,
0x0, 0xa4, 0x2, 0xcf, 0xb0, 0x0, 0x0, 0x0,
0x5f, 0xff, 0xff, 0xe1, 0x0, 0x0, 0x0, 0x0,
0x8d, 0xfe, 0x91, 0x0, 0x0, 0x0, 0x0,
/* U+007A "z" */
0xe, 0xff, 0xff, 0xff, 0xff, 0xf6, 0xd, 0xee,
0xee, 0xee, 0xff, 0xf5, 0x0, 0x0, 0x0, 0x1,
0xef, 0xa0, 0x0, 0x0, 0x0, 0xc, 0xfd, 0x0,
0x0, 0x0, 0x0, 0x8f, 0xf2, 0x0, 0x0, 0x0,
0x5, 0xff, 0x40, 0x0, 0x0, 0x0, 0x2f, 0xf8,
0x0, 0x0, 0x0, 0x0, 0xdf, 0xb0, 0x0, 0x0,
0x0, 0xb, 0xfd, 0x10, 0x0, 0x0, 0x0, 0x7f,
0xf2, 0x0, 0x0, 0x0, 0x4, 0xff, 0x50, 0x0,
0x0, 0x0, 0xe, 0xff, 0xee, 0xee, 0xee, 0xe8,
0xf, 0xff, 0xff, 0xff, 0xff, 0xf9,
/* U+00B0 "°" */
0x0, 0x0, 0x0, 0x0, 0x2, 0xbf, 0xfb, 0x20,
0x1e, 0xc5, 0x5c, 0xe2, 0x9d, 0x0, 0x0, 0xda,
0xd8, 0x0, 0x0, 0x7e, 0xd7, 0x0, 0x0, 0x7e,
0xac, 0x0, 0x0, 0xcb, 0x3f, 0xa2, 0x2a, 0xf3,
0x4, 0xef, 0xfe, 0x40, 0x0, 0x2, 0x20, 0x0
};
/*---------------------
* GLYPH DESCRIPTION
*--------------------*/
static const lv_font_fmt_txt_glyph_dsc_t glyph_dsc[] = {
{.bitmap_index = 0, .adv_w = 0, .box_w = 0, .box_h = 0, .ofs_x = 0, .ofs_y = 0} /* id = 0 reserved */,
{.bitmap_index = 0, .adv_w = 103, .box_w = 0, .box_h = 0, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 0, .adv_w = 223, .box_w = 12, .box_h = 11, .ofs_x = 1, .ofs_y = 3},
{.bitmap_index = 66, .adv_w = 87, .box_w = 4, .box_h = 7, .ofs_x = 1, .ofs_y = -4},
{.bitmap_index = 80, .adv_w = 147, .box_w = 7, .box_h = 3, .ofs_x = 1, .ofs_y = 6},
{.bitmap_index = 91, .adv_w = 87, .box_w = 4, .box_h = 4, .ofs_x = 1, .ofs_y = 0},
{.bitmap_index = 99, .adv_w = 256, .box_w = 14, .box_h = 17, .ofs_x = 1, .ofs_y = 0},
{.bitmap_index = 218, .adv_w = 142, .box_w = 7, .box_h = 17, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 278, .adv_w = 220, .box_w = 13, .box_h = 17, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 389, .adv_w = 220, .box_w = 13, .box_h = 17, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 500, .adv_w = 257, .box_w = 16, .box_h = 17, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 636, .adv_w = 220, .box_w = 13, .box_h = 17, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 747, .adv_w = 237, .box_w = 14, .box_h = 17, .ofs_x = 1, .ofs_y = 0},
{.bitmap_index = 866, .adv_w = 230, .box_w = 14, .box_h = 17, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 985, .adv_w = 247, .box_w = 14, .box_h = 17, .ofs_x = 1, .ofs_y = 0},
{.bitmap_index = 1104, .adv_w = 237, .box_w = 14, .box_h = 17, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 1223, .adv_w = 281, .box_w = 19, .box_h = 17, .ofs_x = -1, .ofs_y = 0},
{.bitmap_index = 1385, .adv_w = 291, .box_w = 15, .box_h = 17, .ofs_x = 2, .ofs_y = 0},
{.bitmap_index = 1513, .adv_w = 278, .box_w = 16, .box_h = 17, .ofs_x = 1, .ofs_y = 0},
{.bitmap_index = 1649, .adv_w = 317, .box_w = 17, .box_h = 17, .ofs_x = 2, .ofs_y = 0},
{.bitmap_index = 1794, .adv_w = 257, .box_w = 13, .box_h = 17, .ofs_x = 2, .ofs_y = 0},
{.bitmap_index = 1905, .adv_w = 244, .box_w = 13, .box_h = 17, .ofs_x = 2, .ofs_y = 0},
{.bitmap_index = 2016, .adv_w = 296, .box_w = 16, .box_h = 17, .ofs_x = 1, .ofs_y = 0},
{.bitmap_index = 2152, .adv_w = 312, .box_w = 15, .box_h = 17, .ofs_x = 2, .ofs_y = 0},
{.bitmap_index = 2280, .adv_w = 119, .box_w = 3, .box_h = 17, .ofs_x = 2, .ofs_y = 0},
{.bitmap_index = 2306, .adv_w = 197, .box_w = 11, .box_h = 17, .ofs_x = -1, .ofs_y = 0},
{.bitmap_index = 2400, .adv_w = 276, .box_w = 16, .box_h = 17, .ofs_x = 2, .ofs_y = 0},
{.bitmap_index = 2536, .adv_w = 228, .box_w = 13, .box_h = 17, .ofs_x = 2, .ofs_y = 0},
{.bitmap_index = 2647, .adv_w = 367, .box_w = 19, .box_h = 17, .ofs_x = 2, .ofs_y = 0},
{.bitmap_index = 2809, .adv_w = 312, .box_w = 15, .box_h = 17, .ofs_x = 2, .ofs_y = 0},
{.bitmap_index = 2937, .adv_w = 323, .box_w = 19, .box_h = 17, .ofs_x = 1, .ofs_y = 0},
{.bitmap_index = 3099, .adv_w = 277, .box_w = 15, .box_h = 17, .ofs_x = 2, .ofs_y = 0},
{.bitmap_index = 3227, .adv_w = 323, .box_w = 19, .box_h = 20, .ofs_x = 1, .ofs_y = -3},
{.bitmap_index = 3417, .adv_w = 279, .box_w = 15, .box_h = 17, .ofs_x = 2, .ofs_y = 0},
{.bitmap_index = 3545, .adv_w = 238, .box_w = 14, .box_h = 17, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 3664, .adv_w = 225, .box_w = 14, .box_h = 17, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 3783, .adv_w = 304, .box_w = 15, .box_h = 17, .ofs_x = 2, .ofs_y = 0},
{.bitmap_index = 3911, .adv_w = 273, .box_w = 19, .box_h = 17, .ofs_x = -1, .ofs_y = 0},
{.bitmap_index = 4073, .adv_w = 432, .box_w = 27, .box_h = 17, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 4303, .adv_w = 258, .box_w = 16, .box_h = 17, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 4439, .adv_w = 248, .box_w = 17, .box_h = 17, .ofs_x = -1, .ofs_y = 0},
{.bitmap_index = 4584, .adv_w = 252, .box_w = 15, .box_h = 17, .ofs_x = 1, .ofs_y = 0},
{.bitmap_index = 4712, .adv_w = 230, .box_w = 12, .box_h = 13, .ofs_x = 1, .ofs_y = 0},
{.bitmap_index = 4790, .adv_w = 262, .box_w = 14, .box_h = 18, .ofs_x = 2, .ofs_y = 0},
{.bitmap_index = 4916, .adv_w = 219, .box_w = 12, .box_h = 13, .ofs_x = 1, .ofs_y = 0},
{.bitmap_index = 4994, .adv_w = 262, .box_w = 14, .box_h = 18, .ofs_x = 1, .ofs_y = 0},
{.bitmap_index = 5120, .adv_w = 235, .box_w = 13, .box_h = 13, .ofs_x = 1, .ofs_y = 0},
{.bitmap_index = 5205, .adv_w = 136, .box_w = 10, .box_h = 18, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 5295, .adv_w = 265, .box_w = 14, .box_h = 18, .ofs_x = 1, .ofs_y = -5},
{.bitmap_index = 5421, .adv_w = 262, .box_w = 13, .box_h = 18, .ofs_x = 2, .ofs_y = 0},
{.bitmap_index = 5538, .adv_w = 107, .box_w = 4, .box_h = 18, .ofs_x = 1, .ofs_y = 0},
{.bitmap_index = 5574, .adv_w = 109, .box_w = 9, .box_h = 23, .ofs_x = -3, .ofs_y = -5},
{.bitmap_index = 5678, .adv_w = 237, .box_w = 13, .box_h = 18, .ofs_x = 2, .ofs_y = 0},
{.bitmap_index = 5795, .adv_w = 107, .box_w = 3, .box_h = 18, .ofs_x = 2, .ofs_y = 0},
{.bitmap_index = 5822, .adv_w = 406, .box_w = 22, .box_h = 13, .ofs_x = 2, .ofs_y = 0},
{.bitmap_index = 5965, .adv_w = 262, .box_w = 13, .box_h = 13, .ofs_x = 2, .ofs_y = 0},
{.bitmap_index = 6050, .adv_w = 244, .box_w = 14, .box_h = 13, .ofs_x = 1, .ofs_y = 0},
{.bitmap_index = 6141, .adv_w = 262, .box_w = 14, .box_h = 18, .ofs_x = 2, .ofs_y = -5},
{.bitmap_index = 6267, .adv_w = 262, .box_w = 14, .box_h = 18, .ofs_x = 1, .ofs_y = -5},
{.bitmap_index = 6393, .adv_w = 157, .box_w = 8, .box_h = 13, .ofs_x = 2, .ofs_y = 0},
{.bitmap_index = 6445, .adv_w = 192, .box_w = 12, .box_h = 13, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 6523, .adv_w = 159, .box_w = 10, .box_h = 16, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 6603, .adv_w = 260, .box_w = 13, .box_h = 13, .ofs_x = 2, .ofs_y = 0},
{.bitmap_index = 6688, .adv_w = 215, .box_w = 15, .box_h = 13, .ofs_x = -1, .ofs_y = 0},
{.bitmap_index = 6786, .adv_w = 345, .box_w = 22, .box_h = 13, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 6929, .adv_w = 212, .box_w = 13, .box_h = 13, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 7014, .adv_w = 215, .box_w = 15, .box_h = 18, .ofs_x = -1, .ofs_y = -5},
{.bitmap_index = 7149, .adv_w = 200, .box_w = 12, .box_h = 13, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 7227, .adv_w = 161, .box_w = 8, .box_h = 10, .ofs_x = 1, .ofs_y = 9}
};
/*---------------------
* CHARACTER MAPPING
*--------------------*/
static const uint8_t glyph_id_ofs_list_0[] = {
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 1, 2, 3, 4, 0,
5, 6, 7, 8, 9, 10, 11, 12,
13, 14
};
/*Collect the unicode lists and glyph_id offsets*/
static const lv_font_fmt_txt_cmap_t cmaps[] =
{
{
.range_start = 32, .range_length = 26, .glyph_id_start = 1,
.unicode_list = NULL, .glyph_id_ofs_list = glyph_id_ofs_list_0, .list_length = 26, .type = LV_FONT_FMT_TXT_CMAP_FORMAT0_FULL
},
{
.range_start = 65, .range_length = 26, .glyph_id_start = 16,
.unicode_list = NULL, .glyph_id_ofs_list = NULL, .list_length = 0, .type = LV_FONT_FMT_TXT_CMAP_FORMAT0_TINY
},
{
.range_start = 97, .range_length = 26, .glyph_id_start = 42,
.unicode_list = NULL, .glyph_id_ofs_list = NULL, .list_length = 0, .type = LV_FONT_FMT_TXT_CMAP_FORMAT0_TINY
},
{
.range_start = 176, .range_length = 1, .glyph_id_start = 68,
.unicode_list = NULL, .glyph_id_ofs_list = NULL, .list_length = 0, .type = LV_FONT_FMT_TXT_CMAP_FORMAT0_TINY
}
};
/*-----------------
* KERNING
*----------------*/
/*Map glyph_ids to kern left classes*/
static const uint8_t kern_left_class_mapping[] =
{
0, 0, 1, 2, 1, 2, 3, 0,
4, 5, 6, 7, 8, 9, 10, 3,
11, 12, 13, 14, 15, 16, 17, 18,
18, 19, 20, 21, 18, 18, 14, 22,
14, 23, 24, 25, 19, 26, 26, 27,
28, 29, 30, 31, 32, 33, 34, 35,
36, 30, 36, 36, 37, 33, 30, 30,
31, 31, 38, 39, 40, 41, 36, 42,
42, 43, 42, 44, 45
};
/*Map glyph_ids to kern right classes*/
static const uint8_t kern_right_class_mapping[] =
{
0, 0, 1, 2, 1, 2, 3, 4,
5, 6, 7, 8, 3, 9, 10, 11,
12, 13, 14, 13, 13, 13, 14, 13,
13, 15, 13, 13, 13, 13, 14, 13,
14, 13, 16, 17, 18, 19, 19, 20,
21, 22, 23, 24, 25, 25, 25, 0,
25, 24, 26, 27, 24, 24, 28, 28,
25, 28, 25, 28, 29, 30, 31, 32,
32, 33, 32, 34, 35
};
/*Kern values between classes*/
static const int8_t kern_class_values[] =
{
1, -3, 3, -7, -5, -8, 3, 0,
-4, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, -3, 0, -5, -5, 4,
4, -3, 0, -5, 4, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, -24, 3, -5,
0, -1, -1, -4, 0, 0, -3, 0,
0, -3, 0, 0, -9, 0, -8, 0,
-10, -13, -13, -7, 0, 0, 0, 0,
-3, 0, 0, 4, 0, 3, -4, 0,
1, -3, 4, -1, 0, 0, 0, -7,
0, -1, 0, 0, 1, 0, 0, 5,
0, -3, 0, -5, 0, -7, 0, 0,
0, -4, 0, 0, 0, 0, 0, -1,
1, -3, -3, 0, 0, 0, 0, 0,
-2, -2, 0, -4, -5, 0, 0, 1,
0, 0, 0, 0, -3, 0, -4, -4,
-4, 0, 0, 0, 0, 0, -2, 0,
0, 0, 0, -3, -5, 0, -6, 4,
8, 0, -10, -1, -5, 0, -1, -18,
4, -3, 0, 0, 4, 1, -3, -20,
0, -20, -3, -33, -3, 11, 0, 5,
0, 0, 0, 0, 1, 0, -7, -5,
0, -12, 0, 0, 0, 0, -2, -2,
0, -2, -5, 0, 0, 0, 0, 0,
-4, 0, -4, 0, -3, -5, -3, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, -3, -3, 0, -5, 2, 4, 0,
0, 0, 0, 0, 0, -3, 0, 0,
3, 0, 0, 0, 0, -4, 0, -4,
-3, -5, 0, 0, 0, 3, 0, -3,
0, 0, 0, 0, -4, -6, 0, -7,
-19, -20, -8, 4, 0, -3, -25, -7,
0, -7, 0, -25, 0, -7, -10, -3,
0, 0, 2, -1, 3, -3, -15, 0,
-19, -9, -8, -9, -12, -5, -10, -1,
-7, -10, 2, 0, 4, 0, 0, 0,
0, 0, 0, 0, 0, 0, -2, 0,
0, -1, 0, -4, 0, -7, -8, -8,
-1, 0, 0, 0, 0, -3, 0, 0,
0, 0, 2, -2, 0, 0, -7, 13,
-3, -16, 0, 4, -6, 0, -19, -2,
-5, 5, 0, -4, 6, 0, -13, -6,
-14, -13, -16, 0, 0, 0, -2, 0,
0, 0, -2, -2, -4, -10, -13, -1,
-36, 0, 1, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, -4, 0, -2, -4, -6, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, -1, 5, -8, 4,
-3, -1, -10, -4, 0, -5, -4, -7,
0, -6, 0, -1, -3, -1, -3, -7,
-5, 0, -3, 0, -8, 0, 0, 0,
-8, 0, -7, 0, -7, -7, 4, 3,
-8, 0, -4, -4, -5, 0, 0, 0,
0, 0, -4, 0, 0, -6, 0, -4,
0, -8, -10, -12, -3, 0, 0, 0,
0, 31, 0, 0, 2, 0, 0, -5,
0, 4, -8, 4, -5, 0, -3, -5,
-12, -3, -3, -3, -1, 0, 0, -1,
0, 0, 0, 0, -4, -3, -3, 0,
-3, 0, -3, 0, 0, 0, -3, -5,
-3, -3, -5, -3, 0, 0, -4, -5,
6, 0, 0, -18, -7, 4, -7, 3,
-12, 0, -3, -6, -1, 2, 0, 0,
-7, 0, 0, -7, 0, -7, -4, -6,
-4, -4, 0, -7, 2, -7, -7, 12,
0, 4, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, -3, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, -3,
0, 0, 0, 0, 0, 0, 0, 0,
0, -6, 0, 0, 0, 0, -5, 0,
0, -4, -4, 0, 0, 0, 0, 0,
-2, 0, 0, 0, 0, 0, -3, 0,
0, -13, 0, -8, 8, 1, -3, -18,
0, 0, -8, -4, -11, 0, -10, 0,
-6, -17, -4, -15, -15, -18, 0, -5,
0, -9, -4, -1, -4, -7, -10, -7,
-14, -16, -9, -4, -3, 12, -8, -14,
0, 1, -12, 0, -19, -3, -4, 1,
0, -5, 0, -3, -25, -5, -20, -4,
-28, 0, 1, 0, -3, 0, 0, 0,
0, -2, -3, -15, -3, 0, -25, -1,
-11, 0, 0, -2, -6, -12, -4, 0,
-3, 0, -17, -4, 0, -13, 0, -12,
-3, -7, -10, -4, -7, -6, 0, -5,
-7, -4, -7, 0, 2, 0, -3, -13,
0, 8, -1, 0, 0, 0, 0, -3,
-8, 0, 0, 0, 0, 0, 0, 0,
-4, 0, -4, 0, 0, -8, -4, 0,
-2, 0, 0, 0, 0, 0, 0, 2,
0, 0, 0, 0, 6, 7, 8, 0,
-4, 0, -3, 4, 0, -4, 0, -4,
0, 0, 0, 0, 0, -4, 0, 0,
-5, -6, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, -4, -4, 0, -6,
-13, -12, -8, 15, 7, 4, -33, -3,
8, -4, 0, -13, 0, -4, -4, -3,
4, -5, -3, -12, -3, 0, -11, 0,
-21, -5, 11, -5, -15, 1, -5, -13,
-13, -4, 15, -9, -14, -10, 12, 0,
1, -28, -3, 4, -7, -3, -14, -6,
-8, -6, -6, -3, 0, 0, -9, -8,
-4, -21, 0, -21, -5, 0, -13, -22,
-1, -12, -7, -13, -11, 10, -7, 0,
-13, 4, 0, 0, -20, 0, -4, -8,
-7, -13, -9, -10, 0, -5, -12, -4,
-9, -7, -12, -4, -7, 0, -12, -4,
0, -4, -8, -9, -10, -11, -15, -5,
-8, -12, -14, -13, 13, -4, 2, -36,
-7, 8, -8, -7, -16, -5, -12, -4,
-6, -3, -4, -8, -12, -1, 0, -25,
0, -23, -9, 9, -15, -26, -8, -13,
-16, -19, -13, 8, -5, 8, -7, 8,
0, 0, -12, -1, 0, -1, 0, 0,
0, -3, 0, 0, 0, 0, 0, -4,
0, 0, 1, 0, -5, 0, 0, 0,
0, -3, -3, -5, 0, 0, 0, 0,
0, 0, -8, -2, 0, 0, 0, -8,
0, -5, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 1,
0, 0, 0, 0, 0, 0, -4, 0,
0, -7, 4, -5, 0, -10, -4, -9,
0, 0, -10, 0, -4, -4, 0, 0,
0, 0, -31, -7, -15, -4, -14, 0,
-2, 0, 0, 0, 0, 0, 0, 0,
0, -6, -7, -3, -7, -4, 8, -3,
-9, -3, -7, -7, 0, -5, -2, -3,
0, 0, -1, 0, 0, -34, -3, -5,
0, -8, 0, 0, -3, -3, 0, 0,
0, 0, 3, 0, -3, -7, -3, 7,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 5, 0, 0,
0, 0, 0, 4, 0, 0, -10, -4,
-8, 0, 0, -11, 0, -4, 0, 0,
0, 0, 0, -37, 0, -8, -14, -19,
0, -6, 0, 0, 0, 0, 0, 0,
0, 0, -4, -6, -2, -6, -4, -4,
5, 19, 7, 8, -10, 5, 16, 5,
11, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, -4, 0, -3, 31,
17, 31, 0, 0, 0, 4, 0, 0,
14, 0, 0, 0, -3, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
-6, -32, -5, -3, -16, -19, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, -9, 4, -4, 3,
7, 4, -12, 0, -1, -3, 4, 0,
0, 0, 0, 0, -10, 0, -3, -3,
-8, 0, -4, 0, -8, -3, 0, -3,
-7, 0, -4, -11, -8, -5, 0, 0,
0, 0, -3, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, -6, -32,
-5, -3, -16, -19, 0, 0, 0, 0,
0, 19, 0, 0, 0, 0, 0, 0,
0, 0, -3, -4, 1, -2, 1, -3,
-10, 1, 8, 1, 3, -15, -5, -9,
0, -6, -15, -7, -10, -16, -15, 0,
-3, -3, -5, -3, 0, -3, -1, 6,
0, 6, -3, 0, 12, 0, 0, 0,
-3, -4, -4, 0, 0, -10, 0, -2,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, -4, -4, 0, -5,
-4, 4, -7, -7, -3, 0, -11, -3,
-8, -3, -5, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
-7, 0, 0, 0, 0, -5, 0, -4,
0, 0, -2, -5, -13, 3, 4, 4,
-1, -11, 3, 6, 3, 12, -10, 0,
-3, 0, -3, -15, 0, 0, -12, -10,
0, -7, 0, -6, 0, -6, 0, -3,
6, 0, -3, -12, -4, 14, -9, 0,
-4, 3, 0, 0, -13, 0, -3, -1,
0, 0, 0, -3, 0, -3, -16, -5,
-8, 0, -12, 0, -4, 0, -7, 0,
2, 0, -4, 0, -4, -12, 0, -4,
4, -5, 1, 0, -5, -3, 0, -5,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, -3, 0, 0, 0, 0, 1, 0,
-4, -4, 0, 0, 0, -24, 1, 17,
12, 7, -15, 3, 16, 0, 14, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0
};
/*Collect the kern class' data in one place*/
static const lv_font_fmt_txt_kern_classes_t kern_classes =
{
.class_pair_values = kern_class_values,
.left_class_mapping = kern_left_class_mapping,
.right_class_mapping = kern_right_class_mapping,
.left_class_cnt = 45,
.right_class_cnt = 35,
};
/*--------------------
* ALL CUSTOM DATA
*--------------------*/
#if LV_VERSION_CHECK(8, 0, 0)
/*Store all the custom data of the font*/
static lv_font_fmt_txt_glyph_cache_t cache;
static const lv_font_fmt_txt_dsc_t font_dsc = {
#else
static lv_font_fmt_txt_dsc_t font_dsc = {
#endif
.glyph_bitmap = glyph_bitmap,
.glyph_dsc = glyph_dsc,
.cmaps = cmaps,
.kern_dsc = &kern_classes,
.kern_scale = 16,
.cmap_num = 4,
.bpp = 4,
.kern_classes = 1,
.bitmap_format = 0,
#if LV_VERSION_CHECK(8, 0, 0)
.cache = &cache
#endif
};
/*-----------------
* PUBLIC FONT
*----------------*/
/*Initialize a public general font descriptor*/
#if LV_VERSION_CHECK(8, 0, 0)
const lv_font_t font_montserrat_24_tiny = {
#else
lv_font_t font_montserrat_24_tiny = {
#endif
.get_glyph_dsc = lv_font_get_glyph_dsc_fmt_txt, /*Function pointer to get glyph's data*/
.get_glyph_bitmap = lv_font_get_bitmap_fmt_txt, /*Function pointer to get glyph's bitmap*/
.line_height = 24, /*The maximum line height required by the font*/
.base_line = 5, /*Baseline measured from the bottom of the line*/
#if !(LVGL_VERSION_MAJOR == 6 && LVGL_VERSION_MINOR == 0)
.subpx = LV_FONT_SUBPX_NONE,
#endif
#if LV_VERSION_CHECK(7, 4, 0) || LVGL_VERSION_MAJOR >= 8
.underline_position = -2,
.underline_thickness = 1,
#endif
.dsc = &font_dsc /*The custom font data. Will be accessed by `get_glyph_bitmap/dsc` */
};
#endif /*#if FONT_MONTSERRAT_24_TINY*/
| [
"[email protected]"
] | |
21d7a48a79783312145343f158b3cf82e7820157 | d40ab179d88ece6807155787f10a3f97a9fafaef | /even number.c | 435a063ed66c56c34ad431af041018077f817d43 | [] | no_license | sheinkiruba/vicky23 | a51edae403dab466315bb87f8e44c8733f23bf3b | 2b8b883b1f2418cc8ae5f9f030e7f4d4f253f4c0 | refs/heads/master | 2021-05-02T02:59:12.683254 | 2018-03-28T11:24:17 | 2018-03-28T11:24:17 | 120,889,962 | 1 | 0 | null | null | null | null | UTF-8 | C | false | false | 234 | c | #include <stdio.h>
int main()
{
int num;
int k;
num=1;
printf("Enter the value of N: ");
scanf("%d",&k);
printf("Even Numbers from 1 to %d:\n",k);
while(num<=k)
{
if(num%2==0)
printf("%d ",num);
num++;
}
return 0;
}
| [
"[email protected]"
] | |
334ed4869c8c0c1208e72766bc8ba1bfad3e66ea | 2adc0c745b9cafbadd79a05bf62e6d2de19aa734 | /week3/ch02.h | 6dc55db5857e4d0f1bc3b07c1a0d7101811fdf35 | [] | no_license | luofulin/TEST | 99ac65c5c87f44b87ac97db39e86725f9910251f | 92f3689a0f312cea0f1ac584340591ff3f82314f | refs/heads/master | 2022-12-20T19:27:48.309221 | 2020-10-12T11:07:28 | 2020-10-12T11:07:28 | 299,291,009 | 0 | 0 | null | null | null | null | UTF-8 | C | false | false | 129 | h | #include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
| [
"[email protected]"
] | |
9954e6aac246a363f92c3c7d18f7ae787067cdbb | a01c6b622872f0ce27ad6e86f839bc5548a830be | /WIELD.C | 4c96a98b3d37e0940bbfa6eb2cded03aa1efc136 | [] | no_license | raylouis/DEV-SAMPLES-C-HackSrc | 1301c0da4a05b4b30a0b5be16663351f224d56f0 | 64ceb3b1e2d7e8963ef0738c0d969ef3b32af033 | refs/heads/master | 2021-09-18T20:53:30.950262 | 2018-07-20T02:15:30 | 2018-07-20T02:15:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C | false | false | 2,468 | c | /* Copyright (c) Stichting Mathematisch Centrum, Amsterdam, 1985. */
/* wield.c - version 1.0.3 */
#include "hack.h"
extern struct obj zeroobj;
setuwep(obj) register struct obj *obj; {
setworn(obj, W_WEP);
}
dowield()
{
register struct obj *wep;
register int res = 0;
multi = 0;
if(!(wep = getobj("#-)", "wield"))) /* nothing */;
else if(uwep == wep)
pline("You are already wielding that!");
else if(uwep && uwep->cursed)
pline("The %s welded to your hand!",
aobjnam(uwep, "are"));
else if(wep == &zeroobj) {
if(uwep == 0){
pline("You are already empty handed.");
} else {
setuwep((struct obj *) 0);
res++;
pline("You are empty handed.");
}
} else if(uarms && wep->otyp == TWO_HANDED_SWORD)
pline("You cannot wield a two-handed sword and wear a shield.");
else if(wep->owornmask & (W_ARMOR | W_RING))
pline("You cannot wield that!");
else {
setuwep(wep);
res++;
if(uwep->cursed)
pline("The %s %s to your hand!",
aobjnam(uwep, "weld"),
(uwep->quan == 1) ? "itself" : "themselves"); /* a3 */
else prinv(uwep);
}
return(res);
}
corrode_weapon(){
if(!uwep || uwep->olet != WEAPON_SYM) return; /* %% */
if(uwep->rustfree)
pline("Your %s not affected.", aobjnam(uwep, "are"));
else {
pline("Your %s!", aobjnam(uwep, "corrode"));
uwep->spe--;
}
}
chwepon(otmp,amount)
register struct obj *otmp;
register amount;
{
register char *color = (amount < 0) ? "black" : "green";
register char *time;
if(!uwep || uwep->olet != WEAPON_SYM) {
strange_feeling(otmp,
(amount > 0) ? "Your hands twitch."
: "Your hands itch.");
return(0);
}
if(uwep->otyp == WORM_TOOTH && amount > 0) {
uwep->otyp = CRYSKNIFE;
pline("Your weapon seems sharper now.");
uwep->cursed = 0;
return(1);
}
if(uwep->otyp == CRYSKNIFE && amount < 0) {
uwep->otyp = WORM_TOOTH;
pline("Your weapon looks duller now.");
return(1);
}
/* there is a (soft) upper limit to uwep->spe */
if(amount > 0 && uwep->spe > 5 && rn2(3)) {
pline("Your %s violently green for a while and then evaporate%s.",
aobjnam(uwep, "glow"), plur(uwep->quan));
while(uwep) /* let all of them disappear */
/* note: uwep->quan = 1 is nogood if unpaid */
useup(uwep);
return(1);
}
if(!rn2(6)) amount *= 2;
time = (amount*amount == 1) ? "moment" : "while";
pline("Your %s %s for a %s.",
aobjnam(uwep, "glow"), color, time);
uwep->spe += amount;
if(amount > 0) uwep->cursed = 0;
return(1);
}
| [
"[email protected]"
] | |
304311eedbd189001f7fe83209e628253883bb1f | 99a40e1735feeeefd5889e9d399dbbabcc928986 | /bsp.h | 6bb1bfea25c8e289c7566be0f989ac8509607bcc | [
"MIT"
] | permissive | CarlosCraveiro/Drivers | 1ed3ed6c68159befe22950e6d23de80b9df98d64 | d27d4c3d28ad4b79f35af1692e2ab65031d8ef24 | refs/heads/main | 2023-07-28T12:14:38.860007 | 2021-07-21T22:54:20 | 2021-07-21T22:54:20 | 397,672,756 | 1 | 0 | MIT | 2021-08-18T16:48:16 | 2021-08-18T16:48:15 | null | UTF-8 | C | false | false | 9,560 | h | /*
* bsp_stm32.h
*
* Created on: May 7, 2021
* Author: leocelente
*
* Description:
* O intuito desse arquivo é separar as funções da HAL
* da lógica da biblioteca, então abstrai transações
* I2C e SPI.
*
* Se a biblioteca usa diretamente a HAL, o código
* vai precisar se mudado para usar em outro microcontrolador,
* sistema (eg BeagleBone) ou mesmo uma alternativa a HAL (eg: LL).
* E a HAL tem muito código repetitivo para funções simples,
* usar essas funções deixa o código mais limpo e evita erros bobos.
*
* Cada arquivo bsp_xxxx.h estaria então relacionado com uma plataforma
* BSP é sigla para Board Support Package ("Pacode de Suporte para Placa")
*
* Essa é do STM32 com HAL*, poderia ter uma para Arduino (bsp_arduino.h) que usaria
* as Wire e SPI. Poderia ter uma linux embarcado (bsp_linux.h) que envolveria
* os /dev/i2c0 /dev/spi0 etc e a biblioteca não iria precisar de mudanças para
* ser utilizada em qualquer uma dessas plataformas
*
* * somente em blocking mode, ainda tenho que pensar em abstrações eficientes
* para interrupts e dma
*/
#ifndef INC_BSP_H_
#define INC_BSP_H_
#include <stdint.h>
#define EXPORT static inline
#include "stm32f1xx_hal.h"
#define TIMEOUT HAL_MAX_DELAY // Tempo limite de transações da HAL em milisegundos
/**
* Define nossa enumeração de erros como a mesma da HAL
* Isso define um padrão: 0 quando não há erros,
* por isso na struct "resultXX_t" veja o uso comum na struct
* "resultXX_t"
*/
typedef HAL_StatusTypeDef error_t;
/**
* Agrupa em uma struct o ponteiro e tamanho de um buffer já existente
* então o buffer deve ser criado antes e depois a buffer_view deve ser
* construida:
* uint8_t buffer[16] = { 0 };
* buffer_view_t b_view = {
* .data = &buffer,
* .size = 16 // melhor ainda, usar sizeof(buffer)
* }
*/
typedef struct {
uint8_t *data;
int size;
} buffer_view_t;
/**
* Agrupa o valor de uma operação de 16 bits e se teve algum erro
* a semantica é de:
* "Resultado tem erros implica result.hasError != 0"
* então na hora de usar fica:
*
* resultado = operação();
* if(resultado.hasError){
* cuida dos erros
* }
*/
typedef struct {
error_t hasError;
uint16_t value;
} result16_t;
/**
* Agrupa o valor de uma operação de 16 bits e se teve algum erro
* mais detalhes na result16_t
*/
typedef struct {
error_t hasError;
uint8_t value;
} result8_t;
EXPORT void delay_ms(uint32_t time) {
HAL_Delay(time);
}
/**
* Essa macro só é definida se o I2C for configurado na CubeIDE
*
*
*
*
*
*
*
*
*/
#ifdef HAL_I2C_MODULE_ENABLED
/**
* Define o tipo da interface i2c como o da HAL
*/
typedef I2C_HandleTypeDef i2c_t;
/**
* Agrupa a interface i2c e o endereço do escravo
* i2c: é um PONTEIRO para o da HAL
* address: Endereço NÃO shiftado do escravo
* i2c_device_t = {
* .i2c = &hi2c1,
* .address = 0x40
* }
*/
typedef struct {
i2c_t *i2c;
uint8_t address;
} i2c_device_t;
/***
* Acesso direto, transmite no barramento do I2C, sem enviar
* endereço de registrador
*/
EXPORT error_t i2c_transmit(i2c_device_t device, buffer_view_t buffer) {
return HAL_I2C_Master_Transmit(device.i2c, (device.address << 1), buffer.data,
buffer.size, TIMEOUT);
}
/***
* Acesso direto, lê o que estiver no barramento do I2C, sem enviar
* endereço de registrador
*/
EXPORT error_t i2c_receive(i2c_device_t device, buffer_view_t buffer) {
return HAL_I2C_Master_Receive(device.i2c, (device.address << 1), buffer.data,
buffer.size, TIMEOUT);
}
/**
* Le N bytes do escravo i2c, onde N é o size do buffer_view que é passado.
* Os valores lidos serão escritos no buffer apontado pelo buffer_view
*/
EXPORT error_t i2c_readN(i2c_device_t device, uint8_t register_address,
buffer_view_t buffer_view) {
return HAL_I2C_Mem_Read(device.i2c, (device.address << 1), register_address,
I2C_MEMADD_SIZE_8BIT, buffer_view.data, buffer_view.size, TIMEOUT);
}
/**
* Le um byte do escravo i2c
*/
EXPORT result8_t i2c_read8(i2c_device_t device, uint8_t register_address) {
uint8_t buffer[1] = { 0 };
buffer_view_t view = { .data = buffer, .size = 1 };
error_t error = i2c_readN(device, register_address, view);
uint8_t value = buffer[0];
result8_t result = { .hasError = error, .value = value };
return result;
}
/**
* Le dois bytes do escravo i2c, retorna como u16
*/
EXPORT result16_t i2c_read16(i2c_device_t device, uint8_t register_address) {
uint8_t buffer[2] = { 0 };
buffer_view_t view = { .data = buffer, .size = sizeof(buffer) };
error_t error = i2c_readN(device, register_address, view);
uint16_t value = (buffer[0] << 8) | buffer[1];
result16_t result = { .hasError = error, .value = value };
return result;
}
EXPORT error_t i2c_writeN(i2c_device_t device, uint8_t register_address,
buffer_view_t buffer_view) {
return HAL_I2C_Mem_Write(device.i2c, (device.address << 1),
register_address, I2C_MEMADD_SIZE_8BIT, buffer_view.data,
buffer_view.size,
TIMEOUT);
}
EXPORT error_t i2c_write8(i2c_device_t device, uint8_t register_address,
uint8_t value) {
uint8_t buffer[1] = { value };
buffer_view_t view = { .data = buffer, .size = 1 };
return i2c_writeN(device, register_address, view);
}
EXPORT error_t i2c_write16(i2c_device_t device, uint8_t register_address,
uint16_t value) {
uint8_t buffer[2] = { 0 };
buffer[0] = (uint8_t) (value & 0xFF00) >> 8;
buffer[1] = (uint8_t) value;
buffer_view_t view = { .data = buffer, .size = sizeof(buffer) };
return i2c_writeN(device, register_address, view);
}
#endif
#ifdef HAL_GPIO_MODULE_ENABLED
typedef struct {
GPIO_TypeDef *port;
uint16_t pin;
} gpio_pin_t;
EXPORT void gpio_low(gpio_pin_t pin) {
HAL_GPIO_WritePin(pin.port, pin.pin, GPIO_PIN_RESET);
}
EXPORT void gpio_high(gpio_pin_t pin) {
HAL_GPIO_WritePin(pin.port, pin.pin, GPIO_PIN_SET);
}
EXPORT void gpio_toggle(gpio_pin_t pin) {
HAL_GPIO_TogglePin(pin.port, pin.pin);
}
#endif
/**
* Essa macro só é definida se o SPI for configurado na CubeIDE
*
*
*
*
*
*
*
*/
#ifdef HAL_SPI_MODULE_ENABLED
typedef SPI_HandleTypeDef spi_t;
typedef struct {
spi_t *spi;
gpio_pin_t pin;
} spi_device_t;
EXPORT error_t spi_readN(spi_device_t device, uint8_t register_address,
buffer_view_t buffer_view) {
gpio_low(device.pin);
error_t error = HAL_SPI_Receive(device.spi, buffer_view.data,
buffer_view.size, TIMEOUT);
gpio_high(device.pin);
return error;
}
EXPORT result8_t spi_read8(spi_device_t device, uint8_t register_address) {
uint8_t buffer[1] = { 0 };
buffer_view_t view = { .data=buffer, .size=1};
error_t error = spi_readN(device, register_address, view);
uint8_t value = buffer[0];
result8_t result = { .hasError = error, .value = value };
return result;
}
EXPORT result16_t spi_read16(spi_device_t device, uint8_t register_address) {
uint8_t buffer[2] = { 0 };
buffer_view_t view = { .data=buffer, .size=sizeof(buffer)};
error_t error = spi_readN(device, register_address, view);
uint16_t value = (buffer[0] << 8) | buffer[1];
result16_t result = { .hasError = error, .value = value };
return result;
}
EXPORT error_t spi_writeN(spi_device_t device, uint8_t register_address,
buffer_view_t buffer_view) {
gpio_low(device.pin);
error_t error = HAL_SPI_Receive(device.spi, buffer_view.data,
buffer_view.size,
TIMEOUT);
gpio_high(device.pin);
return error;
}
EXPORT error_t spi_write8(spi_device_t device, uint8_t register_address,
uint8_t value) {
uint8_t buffer[1] = { value };
buffer_view_t view = {.data=buffer, .size = 1};
return spi_writeN(device, register_address, view);
}
EXPORT error_t spi_write16(spi_device_t device, uint8_t register_address,
uint16_t value) {
uint8_t buffer[2] = { 0 };
buffer[0] = (value & 0xFF00) >> 8;
buffer[1] = (uint8_t) value;
buffer_view_t view = {.data=buffer, .size = sizeof(buffer)};
return spi_writeN(device, register_address, view);
}
// TODO: Implement transceive
EXPORT error_t spi_transceive(spi_device_t device, uint8_t register_address,
buffer_view_t rx_buffer, buffer_view_t tx_buffer) {
if (tx_buffer.size != rx_buffer.size) {
return 1;
}
gpio_low(device.pin);
error_t error = HAL_SPI_TransmitReceive(device.spi, tx_buffer.data,
rx_buffer.data, tx_buffer.size, TIMEOUT);
gpio_high(device.pin);
return error;
}
#endif
/***
* MODULO UART
*
*
*
*
*
*
*
*
*
*/
#ifdef HAL_UART_MODULE_ENABLED
typedef UART_HandleTypeDef uart_t;
typedef struct {
uart_t *uart;
} uart_connection_t;
EXPORT error_t uart_writeN(uart_connection_t conn, buffer_view_t buffer) {
return HAL_UART_Transmit(conn.uart, buffer.data, buffer.size, HAL_MAX_DELAY);
}
EXPORT error_t uart_readN(uart_connection_t conn, buffer_view_t buffer) {
return HAL_UART_Receive(conn.uart, buffer.data, buffer.size, 1000);
}
EXPORT result8_t uart_read8(uart_connection_t conn) {
uint8_t buffer[1] = { 0 };
buffer_view_t view = { .data = buffer, .size = 1 };
result8_t result = { .hasError = 1, .value = 0 };
result.hasError = uart_readN(conn, view);
result.value = view.data[0];
return result;
}
#endif
/***
* MODULO ADC
*
*
*
*
*
*
*
*
*
*/
#ifdef HAL_ADC_MODULE_ENABLED
typedef ADC_HandleTypeDef adc_t;
EXPORT void adc_init(adc_t* adc){
HAL_ADC_Start(adc);
}
EXPORT result16_t adc_read(adc_t* adc){
result16_t out = {.hasError = 1, .value = 0xFF};
out.value = HAL_ADC_GetValue(adc);
out.hasError = adc->ErrorCode; // ignore: erro
return out;
}
#endif
/***
* MODULO PWM
*
*
*
*
*
*
*
*
*
*/
#endif /* INC_BSP_H_ */
| [
"[email protected]"
] | |
4817eacb16bd2c9fbeaac7ce86fe4e1c9a3ba150 | 470d52f669a6b819d43423960c590c97842c8305 | /0x04-more_functions_nested_loops/2-mul.c | 6133430cd24d41072a5075a2f064f1b5b601b782 | [] | no_license | danielchk/holbertonschool-low_level_programming | fcded6bf435abba65314e49b75ab561a82f76e7e | 3b7ee858e46410acdeec589e06e41d07e7ba81f3 | refs/heads/master | 2021-07-25T16:14:13.832220 | 2021-01-14T20:15:58 | 2021-01-14T20:15:58 | 238,483,712 | 0 | 0 | null | null | null | null | UTF-8 | C | false | false | 153 | c | #include "holberton.h"
/**
* mul - Entry point
* @a: input
* @b: input 2
* Return: Always 0 (Success)
*/
int mul(int a, int b)
{
return (a * b);
}
| [
"[email protected]"
] | |
e0b078e1736a49a3fa7e1d2b07a45089993b3245 | 6fd5cae2c3c1e9254aab828e7bd444af2443c1c7 | /linkedlist.c | 6f41aba5598af6b2a53f786668f27081d2d1f5f6 | [
"CC0-1.0"
] | permissive | andrewgasson/libfledgling | 0095a81b706336ba263f5843644b6e6b3e17e419 | 64e9aa75840bf090c115eaf7faf1a87913647cc3 | refs/heads/main | 2023-07-12T10:22:34.262950 | 2021-08-12T02:27:28 | 2021-08-12T02:27:28 | 392,556,618 | 0 | 0 | null | null | null | null | UTF-8 | C | false | false | 1,649 | c | #include <assert.h>
#include <stdlib.h>
#include "linkedlist.h"
int
linkedlistalloc(LinkedList *list)
{
assert(list != NULL);
list->prev = NULL;
list->next = NULL;
list->entry = NULL;
return 1;
}
int
linkedlistappend(LinkedList *list, void *entry)
{
assert(list != NULL);
assert(entry != NULL);
if (list->entry == NULL) {
list->entry = entry;
return 1;
} else {
LinkedList *node;
node = list;
while (node->next != NULL)
node = node->next;
node->next = malloc(sizeof(LinkedList));
if (node->next) {
node->next->prev = node;
node->next->next = NULL;
node->next->entry = entry;
return 1;
} else {
return 0;
}
}
}
// TODO: Errors are a real problem. Might need to create an error library so
// that we never have to return on malloc failure or something...
//
// Right now, this implies there's already an allocated dstlist...
int
linkedlistcopy(LinkedList *dstlist, LinkedList srclist)
{
if (!linkedlistalloc(&dstlist)) {
return 0;
} else {
LinkedList *dstnode;
LinkedList *srcnode;
dstnode = dstlist;
srcnode = &srclist;
while (srcnode) {
if (dstlist->next == NU)
dstlist->entry
}
}
}
void
linkedlistfree(LinkedList *list)
{
//
}
int
linkedlistindex(LinkedList list, void *entry)
{
//
}
int
linkedlistinsert(LinkedList *list, int index, void *entry)
{
//
}
void
linkedlistremove(LinkedList *list, int index)
{
//
}
void
linkedlistreverse(LinkedList *list)
{
//
}
void
linkedlistswap(LinkedList *list, int index0, int index1)
{
//
}
int
linkedlisttally(LinkedList list, void *entry)
{
//
}
void
linkedlistunique(LinkedList *list, void *entry)
{
//
}
| [
"[email protected]"
] | |
e65f4d9c8ecc1b9332c93de5b4dc90d993c6a333 | c672eb33f501ee9836deac8991603cbc362139c8 | /asm/src/parser/node/destroy_list.c | 0833c11f8c725a99d3ba5d09b5061c52f3ebf437 | [] | no_license | aurelienjoncour/Corewar | d859ada97f2db6c7dc6985662234785a290d27ce | 7a938af052413c68009ff76e31d10dcfd247705d | refs/heads/master | 2022-09-08T11:49:28.367953 | 2020-05-27T15:04:49 | 2020-05-27T15:04:49 | 265,006,503 | 0 | 0 | null | null | null | null | UTF-8 | C | false | false | 320 | c | /*
** EPITECH PROJECT, 2020
** CPE_corewar_2019
** File description:
** destroy_list
*/
#include "corewar.h"
void destroy_list(token_t *ptr)
{
free(ptr->token);
if (ptr->prev != NULL)
free(ptr->prev);
if (ptr->next != NULL) {
destroy_list(ptr->next);
} else {
free(ptr);
}
} | [
"[email protected]"
] | |
d7cd3e6bc71bd3999890c422f18b7af92e814dbe | acc5a1aec57ebcf63d1ef050be48879a6c4e77a0 | /cmds/wiz/analyze.c | f34f5734f54e9910d20780fd38decb5c2ede660b | [] | no_license | jrealm/fluffos-web-es2 | b4f6acd5e201cb742f598a4fbe917e40279b4843 | eba5dfa475d1294527aa811415d8fc657e06cb22 | refs/heads/master | 2020-04-11T06:33:28.134104 | 2018-12-27T02:58:14 | 2018-12-27T02:58:14 | 161,584,275 | 7 | 2 | null | null | null | null | BIG5 | C | false | false | 3,245 | c | /* analyze.c
Copyright (C) 1994-2000 Annihilator <[email protected]>
This program is a part of ES2 mudlib. Permission is granted to use,
modify, copy or distribute this program provided this copyright notice
remains intact and subject to the restriction that this program MAY
NOT be used in any way for monetary gain.
Details of terms and conditions is available in the Copyright.ES2 file.
If you don't receive this file along with this program, write to the
primary author of ES2 mudlib: Annihilator <[email protected]>
*/
#include <ansi.h>
inherit F_CLEAN_UP;
int main(object me, string arg)
{
object ob;
string str;
mapping apply, weapon;
if( !arg ) ob = me;
else {
if( !(ob = find_player(arg))
&& !(ob = present(arg, environment(me)))
&& !(ob = find_living(arg)) )
return notify_fail("這裡沒有 " + arg + " 這種生物。\n");
}
str = sprintf("%s的各項能力分析﹕\n", ob->name());
str += HIY "\n<基本值 - 來自屬性>\n" NOR;
str += sprintf("攻擊力\t\t攻勢 %d,技巧 %d,力道 %.2f 公斤\n",
ob->query_ability("intimidate"),
ob->query_ability("attack"),
ob->query_strength("attack") / 1000.0);
str += sprintf("防禦力\t\t守勢 %d,技巧 %d,強度 %.2f 公斤\n",
ob->query_ability("wittiness"),
ob->query_ability("defense"),
ob->query_strength("defense") / 1000.0);
str += sprintf("魔力\t\t能力值 %d﹐強度 %.2f Kw\n", ob->query_ability("magic"),
ob->query_strength("magic") / 1000.0);
str += sprintf("法力\t\t能力值 %d﹐強度 %.2f Kw\n", ob->query_ability("spell"),
ob->query_strength("spell") / 1000.0);
str += HIY "\n<修正值 - 來自技能>\n" NOR;
if( ob->query_skill("force") && ob->skill_mapped("force")!="force" ) {
int skill, modify;
skill = ob->query_skill("force");
modify = skill * ob->query_stat("kee") * 4;
str += sprintf("使用內力 \t%s(攻擊強度 +%.2f Kg)\n",
to_chinese(ob->skill_mapped("force")), (float)modify/1000.0);
}
if( mapp(weapon = ob->query_temp("weapon")) && sizeof(weapon) ) {
string term;
str += "使用武器\t";
foreach(term in keys(weapon)) {
str += sprintf("%s﹐(攻擊能力 %+d)\n\t\t", weapon[term]->name() + "(" + term + ")",
ob->query_skill(term));
}
}
else str += sprintf("徒手攻擊 \t(攻擊能力 %+d)\n", ob->query_skill("unarmed"));
if( mapp(apply = ob->query_temp("apply")) ) {
string term;
int prop, k;
str += HIY "\n<附加值 - 來自裝備,法術等影響>\n" NOR;
k = 0;
foreach(term, prop in apply) {
if( !intp(prop) ) continue;
if( prop ) {
str += sprintf(" %-16s %+d%s", to_chinese(term), prop,
k%2==0 ? "\t" : "\n");
k++;
}
}
}
str += "\n";
write(str);
return 1;
}
int help()
{
write(@TEXT
指令格式﹕analyze [<對象>]
這個指令會列出一些有關指定對象的能力值﹐不指定對象時則列出你自己的
能力值。
TEXT
);
return 1;
}
| [
"[email protected]"
] | |
dcda3efdeaf6442a300f4cbc82c56dc71a3d2ba2 | 4700fe6890025691c2429df598ec25914ec4c7da | /code/server/sv_ccmds.c | 90ff484eefd8cb5a99dbd0b3cf7b2af9d31f242b | [] | no_license | QuakeEngines/xreal | 1e7820f8b29de6fb22aa3e058a3c4ef528c1bb55 | 2fcbf9179fa22dc6e808bb65b879ac2ee7616ebd | refs/heads/master | 2020-07-10T04:18:26.146005 | 2016-10-14T23:06:22 | 2016-10-14T23:06:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C | false | false | 25,313 | c | /*
===========================================================================
Copyright (C) 1999-2005 Id Software, Inc.
Copyright (C) 2006-2008 Robert Beckebans <[email protected]>
This file is part of XreaL source code.
XreaL source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
XreaL source code is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with XreaL source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
#include "server.h"
/*
===============================================================================
OPERATOR CONSOLE ONLY COMMANDS
These commands can only be entered from stdin or by a remote operator datagram
===============================================================================
*/
/*
==================
SV_GetPlayerByHandle
Returns the player with player id or name from Cmd_Argv(1)
==================
*/
static client_t *SV_GetPlayerByHandle(void)
{
client_t *cl;
int i;
char *s;
char cleanName[64];
// make sure server is running
if(!com_sv_running->integer)
{
return NULL;
}
if(Cmd_Argc() < 2)
{
Com_Printf("No player specified.\n");
return NULL;
}
s = Cmd_Argv(1);
// Check whether this is a numeric player handle
for(i = 0; s[i] >= '0' && s[i] <= '9'; i++);
if(!s[i])
{
int plid = atoi(s);
// Check for numeric playerid match
if(plid >= 0 && plid < sv_maxclients->integer)
{
cl = &svs.clients[plid];
if(cl->state)
return cl;
}
}
// check for a name match
for(i = 0, cl = svs.clients; i < sv_maxclients->integer; i++, cl++)
{
if(!cl->state)
{
continue;
}
if(!Q_stricmp(cl->name, s))
{
return cl;
}
Q_strncpyz(cleanName, cl->name, sizeof(cleanName));
Q_CleanStr(cleanName);
if(!Q_stricmp(cleanName, s))
{
return cl;
}
}
Com_Printf("Player %s is not on the server\n", s);
return NULL;
}
/*
==================
SV_GetPlayerByNum
Returns the player with idnum from Cmd_Argv(1)
==================
*/
static client_t *SV_GetPlayerByNum(void)
{
client_t *cl;
int i;
int idnum;
char *s;
// make sure server is running
if(!com_sv_running->integer)
{
return NULL;
}
if(Cmd_Argc() < 2)
{
Com_Printf("No player specified.\n");
return NULL;
}
s = Cmd_Argv(1);
for(i = 0; s[i]; i++)
{
if(s[i] < '0' || s[i] > '9')
{
Com_Printf("Bad slot number: %s\n", s);
return NULL;
}
}
idnum = atoi(s);
if(idnum < 0 || idnum >= sv_maxclients->integer)
{
Com_Printf("Bad client slot: %i\n", idnum);
return NULL;
}
cl = &svs.clients[idnum];
if(!cl->state)
{
Com_Printf("Client %i is not active\n", idnum);
return NULL;
}
return cl;
}
//=========================================================
/*
==================
SV_Map_f
Restart the server on a different map
==================
*/
static void SV_Map_f(void)
{
char *cmd;
char *map;
qboolean killBots, cheat;
char expanded[MAX_QPATH];
char mapname[MAX_QPATH];
map = Cmd_Argv(1);
if(!map)
{
return;
}
// make sure the level exists before trying to change, so that
// a typo at the server console won't end the game
Com_sprintf(expanded, sizeof(expanded), "maps/%s.bsp", map);
if(FS_ReadFile(expanded, NULL) == -1)
{
Com_Printf("Can't find map %s\n", expanded);
return;
}
// force latched values to get set
Cvar_Get("g_gametype", "0", CVAR_SERVERINFO | CVAR_USERINFO | CVAR_LATCH);
cmd = Cmd_Argv(0);
if(Q_stricmpn(cmd, "sp", 2) == 0)
{
Cvar_SetValue("g_gametype", GT_SINGLE_PLAYER);
Cvar_SetValue("g_doWarmup", 0);
// may not set sv_maxclients directly, always set latched
Cvar_SetLatched("sv_maxclients", "8");
cmd += 2;
cheat = qfalse;
killBots = qtrue;
}
else
{
if(!Q_stricmp(cmd, "devmap") || !Q_stricmp(cmd, "spdevmap"))
{
cheat = qtrue;
killBots = qtrue;
}
else
{
cheat = qfalse;
killBots = qfalse;
}
if(sv_gametype->integer == GT_SINGLE_PLAYER)
{
Cvar_SetValue("g_gametype", GT_FFA);
}
}
// save the map name here cause on a map restart we reload the q3config.cfg
// and thus nuke the arguments of the map command
Q_strncpyz(mapname, map, sizeof(mapname));
// start up the map
SV_SpawnServer(mapname, killBots);
// set the cheat value
// if the level was started with "map <levelname>", then
// cheats will not be allowed. If started with "devmap <levelname>"
// then cheats will be allowed
if(cheat)
{
Cvar_Set("sv_cheats", "1");
}
else
{
Cvar_Set("sv_cheats", "0");
}
}
/*
================
SV_MapRestart_f
Completely restarts a level, but doesn't send a new gamestate to the clients.
This allows fair starts with variable load times.
================
*/
static void SV_MapRestart_f(void)
{
int i;
client_t *client;
char *denied;
qboolean isBot;
int delay;
// make sure we aren't restarting twice in the same frame
if(com_frameTime == sv.serverId)
{
return;
}
// make sure server is running
if(!com_sv_running->integer)
{
Com_Printf("Server is not running.\n");
return;
}
if(sv.restartTime)
{
return;
}
if(Cmd_Argc() > 1)
{
delay = atoi(Cmd_Argv(1));
}
else
{
delay = 5;
}
if(delay && !Cvar_VariableValue("g_doWarmup"))
{
sv.restartTime = sv.time + delay * 1000;
SV_SetConfigstring(CS_WARMUP, va("%i", sv.restartTime));
return;
}
// check for changes in variables that can't just be restarted
// check for maxclients change
if(sv_maxclients->modified || sv_gametype->modified)
{
char mapname[MAX_QPATH];
Com_Printf("variable change -- restarting.\n");
// restart the map the slow way
Q_strncpyz(mapname, Cvar_VariableString("mapname"), sizeof(mapname));
SV_SpawnServer(mapname, qfalse);
return;
}
// toggle the server bit so clients can detect that a
// map_restart has happened
svs.snapFlagServerBit ^= SNAPFLAG_SERVERCOUNT;
// generate a new serverid
// TTimo - don't update restartedserverId there, otherwise we won't deal correctly with multiple map_restart
sv.serverId = com_frameTime;
Cvar_Set("sv_serverid", va("%i", sv.serverId));
// reset all the vm data in place without changing memory allocation
// note that we do NOT set sv.state = SS_LOADING, so configstrings that
// had been changed from their default values will generate broadcast updates
sv.state = SS_LOADING;
sv.restarting = qtrue;
SV_RestartGameProgs();
// run a few frames to allow everything to settle
for(i = 0; i < 3; i++)
{
VM_Call(gvm, GAME_RUN_FRAME, sv.time);
sv.time += 100;
svs.time += 100;
}
sv.state = SS_GAME;
sv.restarting = qfalse;
// connect and begin all the clients
for(i = 0; i < sv_maxclients->integer; i++)
{
client = &svs.clients[i];
// send the new gamestate to all connected clients
if(client->state < CS_CONNECTED)
{
continue;
}
if(client->netchan.remoteAddress.type == NA_BOT)
{
isBot = qtrue;
}
else
{
isBot = qfalse;
}
// add the map_restart command
SV_AddServerCommand(client, "map_restart\n");
// connect the client again, without the firstTime flag
denied = VM_ExplicitArgPtr(gvm, VM_Call(gvm, GAME_CLIENT_CONNECT, i, qfalse, isBot));
if(denied)
{
// this generally shouldn't happen, because the client
// was connected before the level change
SV_DropClient(client, denied);
Com_Printf("SV_MapRestart_f(%d): dropped client %i - denied!\n", delay, i);
continue;
}
client->state = CS_ACTIVE;
SV_ClientEnterWorld(client, &client->lastUsercmd);
}
// run another frame to allow things to look at all the players
VM_Call(gvm, GAME_RUN_FRAME, sv.time);
sv.time += 100;
svs.time += 100;
}
//===============================================================
/*
==================
SV_Kick_f
Kick a user off of the server FIXME: move to game
==================
*/
static void SV_Kick_f(void)
{
client_t *cl;
int i;
// make sure server is running
if(!com_sv_running->integer)
{
Com_Printf("Server is not running.\n");
return;
}
if(Cmd_Argc() != 2)
{
Com_Printf("Usage: kick <player name>\nkick all = kick everyone\nkick allbots = kick all bots\n");
return;
}
cl = SV_GetPlayerByHandle();
if(!cl)
{
if(!Q_stricmp(Cmd_Argv(1), "all"))
{
for(i = 0, cl = svs.clients; i < sv_maxclients->integer; i++, cl++)
{
if(!cl->state)
{
continue;
}
if(cl->netchan.remoteAddress.type == NA_LOOPBACK)
{
continue;
}
SV_DropClient(cl, "was kicked");
cl->lastPacketTime = svs.time; // in case there is a funny zombie
}
}
else if(!Q_stricmp(Cmd_Argv(1), "allbots"))
{
for(i = 0, cl = svs.clients; i < sv_maxclients->integer; i++, cl++)
{
if(!cl->state)
{
continue;
}
if(cl->netchan.remoteAddress.type != NA_BOT)
{
continue;
}
SV_DropClient(cl, "was kicked");
cl->lastPacketTime = svs.time; // in case there is a funny zombie
}
}
return;
}
if(cl->netchan.remoteAddress.type == NA_LOOPBACK)
{
SV_SendServerCommand(NULL, "print \"%s\"", "Cannot kick host player\n");
return;
}
SV_DropClient(cl, "was kicked");
cl->lastPacketTime = svs.time; // in case there is a funny zombie
}
#ifndef STANDALONE
// these functions require the auth server which of course is not available anymore for stand-alone games.
/*
==================
SV_Ban_f
Ban a user from being able to play on this server through the auth
server
==================
*/
static void SV_Ban_f(void)
{
client_t *cl;
// make sure server is running
if(!com_sv_running->integer)
{
Com_Printf("Server is not running.\n");
return;
}
if(Cmd_Argc() != 2)
{
Com_Printf("Usage: banUser <player name>\n");
return;
}
cl = SV_GetPlayerByHandle();
if(!cl)
{
return;
}
if(cl->netchan.remoteAddress.type == NA_LOOPBACK)
{
SV_SendServerCommand(NULL, "print \"%s\"", "Cannot kick host player\n");
return;
}
// look up the authorize server's IP
if(!svs.authorizeAddress.ip[0] && svs.authorizeAddress.type != NA_BAD)
{
Com_Printf("Resolving %s\n", AUTHORIZE_SERVER_NAME);
if(!NET_StringToAdr(AUTHORIZE_SERVER_NAME, &svs.authorizeAddress, NA_IP))
{
Com_Printf("Couldn't resolve address\n");
return;
}
svs.authorizeAddress.port = BigShort(PORT_AUTHORIZE);
Com_Printf("%s resolved to %i.%i.%i.%i:%i\n", AUTHORIZE_SERVER_NAME,
svs.authorizeAddress.ip[0], svs.authorizeAddress.ip[1],
svs.authorizeAddress.ip[2], svs.authorizeAddress.ip[3], BigShort(svs.authorizeAddress.port));
}
// otherwise send their ip to the authorize server
if(svs.authorizeAddress.type != NA_BAD)
{
NET_OutOfBandPrint(NS_SERVER, svs.authorizeAddress,
"banUser %i.%i.%i.%i", cl->netchan.remoteAddress.ip[0], cl->netchan.remoteAddress.ip[1],
cl->netchan.remoteAddress.ip[2], cl->netchan.remoteAddress.ip[3]);
Com_Printf("%s was banned from coming back\n", cl->name);
}
}
/*
==================
SV_BanNum_f
Ban a user from being able to play on this server through the auth
server
==================
*/
static void SV_BanNum_f(void)
{
client_t *cl;
// make sure server is running
if(!com_sv_running->integer)
{
Com_Printf("Server is not running.\n");
return;
}
if(Cmd_Argc() != 2)
{
Com_Printf("Usage: banClient <client number>\n");
return;
}
cl = SV_GetPlayerByNum();
if(!cl)
{
return;
}
if(cl->netchan.remoteAddress.type == NA_LOOPBACK)
{
SV_SendServerCommand(NULL, "print \"%s\"", "Cannot kick host player\n");
return;
}
// look up the authorize server's IP
if(!svs.authorizeAddress.ip[0] && svs.authorizeAddress.type != NA_BAD)
{
Com_Printf("Resolving %s\n", AUTHORIZE_SERVER_NAME);
if(!NET_StringToAdr(AUTHORIZE_SERVER_NAME, &svs.authorizeAddress, NA_IP))
{
Com_Printf("Couldn't resolve address\n");
return;
}
svs.authorizeAddress.port = BigShort(PORT_AUTHORIZE);
Com_Printf("%s resolved to %i.%i.%i.%i:%i\n", AUTHORIZE_SERVER_NAME,
svs.authorizeAddress.ip[0], svs.authorizeAddress.ip[1],
svs.authorizeAddress.ip[2], svs.authorizeAddress.ip[3], BigShort(svs.authorizeAddress.port));
}
// otherwise send their ip to the authorize server
if(svs.authorizeAddress.type != NA_BAD)
{
NET_OutOfBandPrint(NS_SERVER, svs.authorizeAddress,
"banUser %i.%i.%i.%i", cl->netchan.remoteAddress.ip[0], cl->netchan.remoteAddress.ip[1],
cl->netchan.remoteAddress.ip[2], cl->netchan.remoteAddress.ip[3]);
Com_Printf("%s was banned from coming back\n", cl->name);
}
}
#endif
/*
==================
SV_RehashBans_f
Load saved bans from file.
==================
*/
void SV_RehashBans_f(void)
{
int index, filelen;
fileHandle_t readfrom;
char *textbuf, *curpos, *maskpos, *newlinepos, *endpos;
char filepath[MAX_QPATH];
serverBansCount = 0;
if(!(curpos = Cvar_VariableString("fs_game")) || !*curpos)
curpos = BASEGAME;
Com_sprintf(filepath, sizeof(filepath), "%s/%s", curpos, SERVER_BANFILE);
if((filelen = FS_SV_FOpenFileRead(filepath, &readfrom)) >= 0)
{
if(filelen < 2)
{
// Don't bother if file is too short.
FS_FCloseFile(readfrom);
return;
}
curpos = textbuf = Z_Malloc(filelen);
filelen = FS_Read(textbuf, filelen, readfrom);
FS_FCloseFile(readfrom);
endpos = textbuf + filelen;
for(index = 0; index < SERVER_MAXBANS && curpos + 2 < endpos; index++)
{
// find the end of the address string
for(maskpos = curpos + 2; maskpos < endpos && *maskpos != ' '; maskpos++);
if(maskpos + 1 >= endpos)
break;
*maskpos = '\0';
maskpos++;
// find the end of the subnet specifier
for(newlinepos = maskpos; newlinepos < endpos && *newlinepos != '\n'; newlinepos++);
if(newlinepos >= endpos)
break;
*newlinepos = '\0';
if(NET_StringToAdr(curpos + 2, &serverBans[index].ip, NA_UNSPEC))
{
serverBans[index].isexception = !(curpos[0] == '0');
serverBans[index].subnet = atoi(maskpos);
if(serverBans[index].ip.type == NA_IP && (serverBans[index].subnet < 0 || serverBans[index].subnet > 32))
{
serverBans[index].subnet = 32;
}
else if(serverBans[index].ip.type == NA_IP6 && (serverBans[index].subnet < 0 || serverBans[index].subnet > 128))
{
serverBans[index].subnet = 128;
}
}
curpos = newlinepos + 1;
}
serverBansCount = index;
Z_Free(textbuf);
}
}
/*
==================
SV_BanAddr_f
Ban a user from being able to play on this server based on his ip address.
==================
*/
static void SV_AddBanToList(qboolean isexception)
{
char *banstring, *suffix;
netadr_t ip;
int argc, mask;
fileHandle_t writeto;
argc = Cmd_Argc();
if(argc < 2 || argc > 3)
{
Com_Printf("Usage: %s (ip[/subnet] | clientnum [subnet])\n", Cmd_Argv(0));
return;
}
if(serverBansCount > sizeof(serverBans) / sizeof(*serverBans))
{
Com_Printf("Error: Maximum number of bans/exceptions exceeded.\n");
return;
}
banstring = Cmd_Argv(1);
if(strchr(banstring, '.') || strchr(banstring, ':'))
{
// This is an ip address, not a client num.
// Look for a CIDR-Notation suffix
suffix = strchr(banstring, '/');
if(suffix)
{
*suffix = '\0';
suffix++;
}
if(!NET_StringToAdr(banstring, &ip, NA_UNSPEC))
{
Com_Printf("Error: Invalid address %s\n", banstring);
return;
}
}
else
{
client_t *cl;
// client num.
if(!com_sv_running->integer)
{
Com_Printf("Server is not running.\n");
return;
}
cl = SV_GetPlayerByNum();
if(!cl)
{
Com_Printf("Error: Playernum %s does not exist.\n", Cmd_Argv(1));
return;
}
ip = cl->netchan.remoteAddress;
if(argc == 3)
suffix = Cmd_Argv(2);
else
suffix = NULL;
}
if(ip.type != NA_IP && ip.type != NA_IP6)
{
Com_Printf("Error: Can ban players connected via the internet only.\n");
return;
}
if(suffix)
{
mask = atoi(suffix);
if(ip.type == NA_IP)
{
if(mask < 0 || mask > 32)
mask = 32;
}
else
{
if(mask < 0 || mask > 128)
mask = 128;
}
}
else if(ip.type == NA_IP)
mask = 32;
else
mask = 128;
serverBans[serverBansCount].ip = ip;
serverBans[serverBansCount].subnet = mask;
serverBans[serverBansCount].isexception = isexception;
Com_Printf("Added %s: %s/%d\n", isexception ? "ban exception" : "ban", NET_AdrToString(ip), mask);
// Write out the ban information.
if((writeto = FS_FOpenFileAppend(SERVER_BANFILE)))
{
char writebuf[128];
Com_sprintf(writebuf, sizeof(writebuf), "%d %s %d\n", isexception, NET_AdrToString(ip), mask);
FS_Write(writebuf, strlen(writebuf), writeto);
FS_FCloseFile(writeto);
}
serverBansCount++;
}
static void SV_DelBanFromList(qboolean isexception)
{
int index, count, todel;
fileHandle_t writeto;
if(Cmd_Argc() != 2)
{
Com_Printf("Usage: %s <num>\n", Cmd_Argv(0));
return;
}
todel = atoi(Cmd_Argv(1));
if(todel < 0 || todel > serverBansCount)
return;
for(index = count = 0; index < serverBansCount; index++)
{
if(serverBans[index].isexception == isexception)
{
count++;
if(count == todel)
break;
}
}
if(index == serverBansCount - 1)
serverBansCount--;
else if(index < sizeof(serverBans) / sizeof(*serverBans) - 1)
{
memmove(serverBans + index, serverBans + index + 1, (serverBansCount - index - 1) * sizeof(*serverBans));
serverBansCount--;
}
else
{
Com_Printf("Error: No such entry #%d\n", todel);
return;
}
// Write out the ban information.
if((writeto = FS_FOpenFileWrite(SERVER_BANFILE)))
{
char writebuf[128];
serverBan_t *curban;
for(index = 0; index < serverBansCount; index++)
{
curban = &serverBans[index];
Com_sprintf(writebuf, sizeof(writebuf), "%d %s %d\n",
curban->isexception, NET_AdrToString(curban->ip), curban->subnet);
FS_Write(writebuf, strlen(writebuf), writeto);
}
FS_FCloseFile(writeto);
}
}
static void SV_ListBans_f(void)
{
int index, count;
serverBan_t *ban;
// List all bans
for(index = count = 0; index < serverBansCount; index++)
{
ban = &serverBans[index];
if(!ban->isexception)
{
count++;
Com_Printf("Ban #%d: %s/%d\n", count, NET_AdrToString(ban->ip), ban->subnet);
}
}
// List all exceptions
for(index = count = 0; index < serverBansCount; index++)
{
ban = &serverBans[index];
if(ban->isexception)
{
count++;
Com_Printf("Except #%d: %s/%d\n", count, NET_AdrToString(ban->ip), ban->subnet);
}
}
}
static void SV_FlushBans_f(void)
{
fileHandle_t blankf;
serverBansCount = 0;
// empty the ban file.
blankf = FS_FOpenFileWrite(SERVER_BANFILE);
if(blankf)
FS_FCloseFile(blankf);
}
static void SV_BanAddr_f(void)
{
SV_AddBanToList(qfalse);
}
static void SV_ExceptAddr_f(void)
{
SV_AddBanToList(qtrue);
}
static void SV_BanDel_f(void)
{
SV_DelBanFromList(qfalse);
}
static void SV_ExceptDel_f(void)
{
SV_DelBanFromList(qtrue);
}
/*
==================
SV_KickNum_f
Kick a user off of the server FIXME: move to game
==================
*/
static void SV_KickNum_f(void)
{
client_t *cl;
// make sure server is running
if(!com_sv_running->integer)
{
Com_Printf("Server is not running.\n");
return;
}
if(Cmd_Argc() != 2)
{
Com_Printf("Usage: kicknum <client number>\n");
return;
}
cl = SV_GetPlayerByNum();
if(!cl)
{
return;
}
if(cl->netchan.remoteAddress.type == NA_LOOPBACK)
{
SV_SendServerCommand(NULL, "print \"%s\"", "Cannot kick host player\n");
return;
}
SV_DropClient(cl, "was kicked");
cl->lastPacketTime = svs.time; // in case there is a funny zombie
}
/*
================
SV_Status_f
================
*/
static void SV_Status_f(void)
{
int i, j, l;
client_t *cl;
playerState_t *ps;
const char *s;
int ping;
// make sure server is running
if(!com_sv_running->integer)
{
Com_Printf("Server is not running.\n");
return;
}
Com_Printf("map: %s\n", sv_mapname->string);
Com_Printf("num score ping name lastmsg address qport rate\n");
Com_Printf("--- ----- ---- --------------- ------- --------------------- ----- -----\n");
for(i = 0, cl = svs.clients; i < sv_maxclients->integer; i++, cl++)
{
if(!cl->state)
continue;
Com_Printf("%3i ", i);
ps = SV_GameClientNum(i);
Com_Printf("%5i ", ps->persistant[PERS_SCORE]);
if(cl->state == CS_CONNECTED)
Com_Printf("CNCT ");
else if(cl->state == CS_ZOMBIE)
Com_Printf("ZMBI ");
else
{
ping = cl->ping < 9999 ? cl->ping : 9999;
Com_Printf("%4i ", ping);
}
Com_Printf("%s", cl->name);
// TTimo adding a ^7 to reset the color
// NOTE: colored names in status breaks the padding (WONTFIX)
Com_Printf("^7");
l = 16 - strlen(cl->name);
for(j = 0; j < l; j++)
Com_Printf(" ");
Com_Printf("%7i ", svs.time - cl->lastPacketTime);
s = NET_AdrToString(cl->netchan.remoteAddress);
Com_Printf("%s", s);
l = 22 - strlen(s);
for(j = 0; j < l; j++)
Com_Printf(" ");
Com_Printf("%5i", cl->netchan.qport);
Com_Printf(" %5i", cl->rate);
Com_Printf("\n");
}
Com_Printf("\n");
}
/*
==================
SV_ConSay_f
==================
*/
static void SV_ConSay_f(void)
{
char *p;
char text[1024];
// make sure server is running
if(!com_sv_running->integer)
{
Com_Printf("Server is not running.\n");
return;
}
if(Cmd_Argc() < 2)
{
return;
}
strcpy(text, "console: ");
p = Cmd_Args();
if(*p == '"')
{
p++;
p[strlen(p) - 1] = 0;
}
strcat(text, p);
SV_SendServerCommand(NULL, "chat \"%s\"", text);
}
/*
==================
SV_Heartbeat_f
Also called by SV_DropClient, SV_DirectConnect, and SV_SpawnServer
==================
*/
void SV_Heartbeat_f(void)
{
svs.nextHeartbeatTime = -9999999;
}
/*
===========
SV_Serverinfo_f
Examine the serverinfo string
===========
*/
static void SV_Serverinfo_f(void)
{
Com_Printf("Server info settings:\n");
Info_Print(Cvar_InfoString(CVAR_SERVERINFO));
}
/*
===========
SV_Systeminfo_f
Examine or change the serverinfo string
===========
*/
static void SV_Systeminfo_f(void)
{
Com_Printf("System info settings:\n");
Info_Print(Cvar_InfoString(CVAR_SYSTEMINFO));
}
/*
===========
SV_DumpUser_f
Examine all a users info strings FIXME: move to game
===========
*/
static void SV_DumpUser_f(void)
{
client_t *cl;
// make sure server is running
if(!com_sv_running->integer)
{
Com_Printf("Server is not running.\n");
return;
}
if(Cmd_Argc() != 2)
{
Com_Printf("Usage: info <userid>\n");
return;
}
cl = SV_GetPlayerByHandle();
if(!cl)
{
return;
}
Com_Printf("userinfo\n");
Com_Printf("--------\n");
Info_Print(cl->userinfo);
}
/*
=================
SV_KillServer
=================
*/
static void SV_KillServer_f(void)
{
SV_Shutdown("killserver");
}
//===========================================================
/*
==================
SV_AddOperatorCommands
==================
*/
void SV_AddOperatorCommands(void)
{
static qboolean initialized;
if(initialized)
{
return;
}
initialized = qtrue;
Cmd_AddCommand("heartbeat", SV_Heartbeat_f);
Cmd_AddCommand("kick", SV_Kick_f);
#ifndef STANDALONE
if(!Cvar_VariableIntegerValue("com_standalone"))
{
Cmd_AddCommand("banUser", SV_Ban_f);
Cmd_AddCommand("banClient", SV_BanNum_f);
}
#endif
Cmd_AddCommand("clientkick", SV_KickNum_f);
Cmd_AddCommand("status", SV_Status_f);
Cmd_AddCommand("serverinfo", SV_Serverinfo_f);
Cmd_AddCommand("systeminfo", SV_Systeminfo_f);
Cmd_AddCommand("dumpuser", SV_DumpUser_f);
Cmd_AddCommand("map_restart", SV_MapRestart_f);
Cmd_AddCommand("sectorlist", SV_SectorList_f);
Cmd_AddCommand("map", SV_Map_f);
Cmd_AddCommand("devmap", SV_Map_f);
Cmd_AddCommand("spmap", SV_Map_f);
Cmd_AddCommand("spdevmap", SV_Map_f);
Cmd_AddCommand("killserver", SV_KillServer_f);
if(com_dedicated->integer)
{
Cmd_AddCommand("say", SV_ConSay_f);
}
Cmd_AddCommand("rehashbans", SV_RehashBans_f);
Cmd_AddCommand("listbans", SV_ListBans_f);
Cmd_AddCommand("banaddr", SV_BanAddr_f);
Cmd_AddCommand("exceptaddr", SV_ExceptAddr_f);
Cmd_AddCommand("bandel", SV_BanDel_f);
Cmd_AddCommand("exceptdel", SV_ExceptDel_f);
Cmd_AddCommand("flushbans", SV_FlushBans_f);
}
/*
==================
SV_RemoveOperatorCommands
==================
*/
void SV_RemoveOperatorCommands(void)
{
#if 0
// removing these won't let the server start again
Cmd_RemoveCommand("heartbeat");
Cmd_RemoveCommand("kick");
Cmd_RemoveCommand("banUser");
Cmd_RemoveCommand("banClient");
Cmd_RemoveCommand("status");
Cmd_RemoveCommand("serverinfo");
Cmd_RemoveCommand("systeminfo");
Cmd_RemoveCommand("dumpuser");
Cmd_RemoveCommand("map_restart");
Cmd_RemoveCommand("sectorlist");
Cmd_RemoveCommand("say");
#endif
}
| [
"[email protected]"
] | |
707fde22c68d5a02dcfc3202319cf357a2a16ebf | 89bc3a820a9e46f8d38792eda3993b3cf1769a72 | /test/deposit_test.c | 41b4c5ec19949822ffc8ca3f13df2141d22c3a3a | [] | no_license | denis-oficcial/deposit-calc | 01d60e32f97decf2e49d839e3d590ea20f21b873 | a69020aa32cee14de538ee65b14d246b538d7ad1 | refs/heads/master | 2021-01-22T06:55:09.898117 | 2017-05-22T08:43:52 | 2017-05-22T08:43:52 | 81,795,327 | 0 | 0 | null | null | null | null | UTF-8 | C | false | false | 227 | c | #include <stdio.h>
#include <ctest.h>
#include <deposit.h>
CTEST(deposit_test, percent_correct)
{
int sum = 123;
int time = 35;
if (time >= 31 && time <= 120){
ASSERT_EQUAL(125, sum+(sum*(0.02)));
}
}
| [
"[email protected]"
] | |
aa130fee3811462a095f67798941901618b75f6e | 539918132b1f20dbe9fbfa22d0592478aba5888d | /Hackathon_070108_碰碰博士_DrPoom/下位机/poom_car_liteos_project/User/dht11/bsp_dht11.c | 70cc34a1644203e2640d2756b6cdcaa7040ef0d9 | [
"BSD-3-Clause"
] | permissive | duguhan520/LiteOS_Hackathon | 5e45dccb10dae032cfb6e9dd638eed971a38082b | 60b510e46b13f57e6502be26248dfb80317346f8 | refs/heads/master | 2021-01-13T12:17:10.252471 | 2017-01-08T12:55:54 | 2017-01-08T12:55:54 | 78,322,617 | 0 | 0 | null | 2017-01-08T05:05:57 | 2017-01-08T05:05:57 | null | GB18030 | C | false | false | 5,270 | c | #include "bsp_dht11.h"
#include "common.h"
static void DHT11_GPIO_Config ( void );
static void DHT11_Mode_IPU ( void );
static void DHT11_Mode_Out_PP ( void );
static uint8_t DHT11_ReadByte ( void );
/**
* @brief DHT11 初始化函数
* @param 无
* @retval 无
*/
void DHT11_Init ( void )
{
DHT11_GPIO_Config ();
macDHT11_Dout_1; // 拉高GPIOB10
}
/*
* 函数名:DHT11_GPIO_Config
* 描述 :配置DHT11用到的I/O口
* 输入 :无
* 输出 :无
*/
static void DHT11_GPIO_Config ( void )
{
/*定义一个GPIO_InitTypeDef类型的结构体*/
GPIO_InitTypeDef GPIO_InitStructure;
/*开启macDHT11_Dout_GPIO_PORT的外设时钟*/
macDHT11_Dout_SCK_APBxClock_FUN ( macDHT11_Dout_GPIO_CLK, ENABLE );
/*选择要控制的macDHT11_Dout_GPIO_PORT引脚*/
GPIO_InitStructure.GPIO_Pin = macDHT11_Dout_GPIO_PIN;
/*设置引脚模式为通用推挽输出*/
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
/*设置引脚速率为50MHz */
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
/*调用库函数,初始化macDHT11_Dout_GPIO_PORT*/
GPIO_Init ( macDHT11_Dout_GPIO_PORT, &GPIO_InitStructure );
}
/*
* 函数名:DHT11_Mode_IPU
* 描述 :使DHT11-DATA引脚变为上拉输入模式
* 输入 :无
* 输出 :无
*/
static void DHT11_Mode_IPU(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
/*选择要控制的macDHT11_Dout_GPIO_PORT引脚*/
GPIO_InitStructure.GPIO_Pin = macDHT11_Dout_GPIO_PIN;
/*设置引脚模式为浮空输入模式*/
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU ;
/*调用库函数,初始化macDHT11_Dout_GPIO_PORT*/
GPIO_Init(macDHT11_Dout_GPIO_PORT, &GPIO_InitStructure);
}
/*
* 函数名:DHT11_Mode_Out_PP
* 描述 :使DHT11-DATA引脚变为推挽输出模式
* 输入 :无
* 输出 :无
*/
static void DHT11_Mode_Out_PP(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
/*选择要控制的macDHT11_Dout_GPIO_PORT引脚*/
GPIO_InitStructure.GPIO_Pin = macDHT11_Dout_GPIO_PIN;
/*设置引脚模式为通用推挽输出*/
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
/*设置引脚速率为50MHz */
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
/*调用库函数,初始化macDHT11_Dout_GPIO_PORT*/
GPIO_Init(macDHT11_Dout_GPIO_PORT, &GPIO_InitStructure);
}
/*
* 从DHT11读取一个字节,MSB先行
*/
static uint8_t DHT11_ReadByte ( void )
{
uint8_t i, temp=0;
for(i=0;i<8;i++)
{
/*每bit以50us低电平标置开始,轮询直到从机发出 的50us 低电平 结束*/
while(macDHT11_Dout_IN()==Bit_RESET);
/*DHT11 以26~28us的高电平表示“0”,以70us高电平表示“1”,
*通过检测 x us后的电平即可区别这两个状 ,x 即下面的延时
*/
Delay_us(40); //延时x us 这个延时需要大于数据0持续的时间即可
if(macDHT11_Dout_IN()==Bit_SET)/* x us后仍为高电平表示数据“1” */
{
/* 等待数据1的高电平结束 */
while(macDHT11_Dout_IN()==Bit_SET);
temp|=(uint8_t)(0x01<<(7-i)); //把第7-i位置1,MSB先行
}
else // x us后为低电平表示数据“0”
{
temp&=(uint8_t)~(0x01<<(7-i)); //把第7-i位置0,MSB先行
}
}
return temp;
}
/*
* 一次完整的数据传输为40bit,高位先出
* 8bit 湿度整数 + 8bit 湿度小数 + 8bit 温度整数 + 8bit 温度小数 + 8bit 校验和
*/
uint8_t DHT11_Read_TempAndHumidity(DHT11_Data_TypeDef *DHT11_Data)
{
/*输出模式*/
DHT11_Mode_Out_PP();
/*主机拉低*/
macDHT11_Dout_0;
/*延时18ms*/
Delay_ms(18);
/*总线拉高 主机延时30us*/
macDHT11_Dout_1;
Delay_us(30); //延时30us
/*主机设为输入 判断从机响应信号*/
DHT11_Mode_IPU();
/*判断从机是否有低电平响应信号 如不响应则跳出,响应则向下运行*/
if(macDHT11_Dout_IN()==Bit_RESET)
{
/*轮询直到从机发出 的80us 低电平 响应信号结束*/
while(macDHT11_Dout_IN()==Bit_RESET);
/*轮询直到从机发出的 80us 高电平 标置信号结束*/
while(macDHT11_Dout_IN()==Bit_SET);
/*开始接收数据*/
DHT11_Data->humi_int= DHT11_ReadByte();
DHT11_Data->humi_deci= DHT11_ReadByte();
DHT11_Data->temp_int= DHT11_ReadByte();
DHT11_Data->temp_deci= DHT11_ReadByte();
DHT11_Data->check_sum= DHT11_ReadByte();
/*读取结束,引脚改为输出模式*/
DHT11_Mode_Out_PP();
/*主机拉高*/
macDHT11_Dout_1;
/*检查读取的数据是否正确*/
if(DHT11_Data->check_sum == DHT11_Data->humi_int + DHT11_Data->humi_deci + DHT11_Data->temp_int+ DHT11_Data->temp_deci)
return SUCCESS;
else
return ERROR;
}
else
return ERROR;
}
/*************************************END OF FILE******************************/
| [
"[email protected]"
] | |
0e99945c1b6957cce683e35e6521d8d87f6b0be2 | e63f3666a9737f971903c9a0f16e59e17e3b633e | /ScanServer_v2.1/ScanServerMessageRouter/ScanServerMessageRouter_i.c | 882a64dcec7ffe25f61e11ef5905ca8d8f6c05f5 | [] | no_license | kryssb/SySal2000 | 185687bf3b3f96ac6206829261e624efe88361c8 | caa9764c5f0f9ae92d086535df25b86070120a40 | refs/heads/master | 2022-07-30T06:29:06.340578 | 2020-11-13T13:21:45 | 2020-11-13T13:21:45 | 312,532,909 | 0 | 0 | null | null | null | null | UTF-8 | C | false | false | 2,314 | c |
/* this ALWAYS GENERATED file contains the IIDs and CLSIDs */
/* link this file in with the server and any clients */
/* File created by MIDL compiler version 6.00.0361 */
/* at Thu Sep 06 08:30:36 2007
*/
/* Compiler settings for .\ScanServerMessageRouter.idl:
Oicf, W1, Zp8, env=Win32 (32b run)
protocol : dce , ms_ext, c_ext, robust
error checks: allocation ref bounds_check enum stub_data
VC __declspec() decoration level:
__declspec(uuid()), __declspec(selectany), __declspec(novtable)
DECLSPEC_UUID(), MIDL_INTERFACE()
*/
//@@MIDL_FILE_HEADING( )
#if !defined(_M_IA64) && !defined(_M_AMD64)
#pragma warning( disable: 4049 ) /* more than 64k source lines */
#ifdef __cplusplus
extern "C"{
#endif
#include <rpc.h>
#include <rpcndr.h>
#ifdef _MIDL_USE_GUIDDEF_
#ifndef INITGUID
#define INITGUID
#include <guiddef.h>
#undef INITGUID
#else
#include <guiddef.h>
#endif
#define MIDL_DEFINE_GUID(type,name,l,w1,w2,b1,b2,b3,b4,b5,b6,b7,b8) \
DEFINE_GUID(name,l,w1,w2,b1,b2,b3,b4,b5,b6,b7,b8)
#else // !_MIDL_USE_GUIDDEF_
#ifndef __IID_DEFINED__
#define __IID_DEFINED__
typedef struct _IID
{
unsigned long x;
unsigned short s1;
unsigned short s2;
unsigned char c[8];
} IID;
#endif // __IID_DEFINED__
#ifndef CLSID_DEFINED
#define CLSID_DEFINED
typedef IID CLSID;
#endif // CLSID_DEFINED
#define MIDL_DEFINE_GUID(type,name,l,w1,w2,b1,b2,b3,b4,b5,b6,b7,b8) \
const type name = {l,w1,w2,{b1,b2,b3,b4,b5,b6,b7,b8}}
#endif !_MIDL_USE_GUIDDEF_
MIDL_DEFINE_GUID(IID, IID_IScanServerMessageRouter,0xCE7FD743,0x3049,0x4661,0xB1,0x58,0xF7,0x50,0x6B,0x11,0x14,0x5D);
MIDL_DEFINE_GUID(IID, IID_ISySalObject,0xC022EEAD,0x748A,0x11D3,0xA4,0x7B,0xE8,0x9C,0x0B,0xCE,0x97,0x20);
MIDL_DEFINE_GUID(IID, IID_IScanServer,0x32E3C1FF,0x0C60,0x45B7,0xB6,0x6F,0x36,0xDB,0x81,0x62,0x76,0xDD);
MIDL_DEFINE_GUID(IID, LIBID_ScanServerMessageRouter,0x01842049,0x1c79,0x449a,0x8a,0x0e,0x4c,0xfe,0x63,0x8d,0xbd,0x57);
MIDL_DEFINE_GUID(CLSID, CLSID_ScanServerMessageRouter,0xf1aa9e69,0x39fc,0x4a61,0x80,0x96,0xa0,0x34,0xce,0xab,0xc0,0xe9);
#undef MIDL_DEFINE_GUID
#ifdef __cplusplus
}
#endif
#endif /* !defined(_M_IA64) && !defined(_M_AMD64)*/
| [
"[email protected]"
] | |
b82ce88ee30b4e6dd5c29783196ac0d32599f61b | 9ce4292954000fd66bcdbd0797a280c306308d08 | /books/BLP/ch12/thread6a.c | de18985d129b22c2a65abd7dfe3405c8225c621b | [
"MIT"
] | permissive | JiniousChoi/encyclopedia-in-code | 0c786f2405bfc1d33291715d9574cae625ae45be | 77bc551a03a2a3e3808e50016ece14adb5cfbd96 | refs/heads/master | 2021-06-27T07:50:10.789732 | 2020-05-29T12:50:46 | 2020-05-29T12:50:46 | 137,426,553 | 2 | 0 | MIT | 2020-10-13T08:56:12 | 2018-06-15T01:29:31 | Python | UTF-8 | C | false | false | 1,878 | c | #include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>
#ifndef _POSIX_THREAD_PRIORITY_SCHEDULING
#error "Sorry, your system does not support thread priority scheduling"
#endif
void *thread_function(void *arg);
char message[] = "Hello World";
int thread_finished = 0;
int main() {
int res;
pthread_t a_thread;
void *thread_result;
int max_priority, min_priority;
struct sched_param scheduling_value;
pthread_attr_t thread_attr;
res = pthread_attr_init(&thread_attr);
if (res != 0) {
perror("Attribute creation failed");
exit(EXIT_FAILURE);
}
res = pthread_attr_setdetachstate(&thread_attr, PTHREAD_CREATE_DETACHED);
if (res != 0) {
perror("Setting detached attribute failed");
exit(EXIT_FAILURE);
}
res = pthread_attr_setschedpolicy(&thread_attr, SCHED_OTHER);
if (res != 0) {
perror("Setting schedpolicy failed");
exit(EXIT_FAILURE);
}
max_priority = sched_get_priority_max(SCHED_OTHER);
min_priority = sched_get_priority_min(SCHED_OTHER);
scheduling_value.sched_priority = min_priority;
res = pthread_attr_setschedparam(&thread_attr, &scheduling_value);
if (res != 0) {
perror("Setting schedpolicy failed");
exit(EXIT_FAILURE);
}
printf("Scheduling priority set to %d, max allowed was %d\n", min_priority, max_priority);
res = pthread_create(&a_thread, &thread_attr, thread_function, (void *)message);
if (res != 0) {
perror("Thread creation failed");
exit(EXIT_FAILURE);
}
(void)pthread_attr_destroy(&thread_attr);
while(!thread_finished) {
printf("Waiting for thread...\n");
sleep(1);
}
printf("Thread finished, bye!\n");
exit(EXIT_SUCCESS);
}
void *thread_function(void *arg) {
printf("thread_function is running. Argument was %s\n", (char *)arg);
sleep(4);
thread_finished = 1;
pthread_exit(NULL);
}
| [
"[email protected]"
] | |
9cc65806a9d33fbe904901adb30f3316e6f6a011 | bb75ce61e834e7ec3202f348821afe102eca9bc3 | /usr/src/contrib/news/inn/lib/xrealloc.c | a6ee18bb73660db756f17de3b570f73210ca99a9 | [
"LicenseRef-scancode-warranty-disclaimer",
"BSD-4-Clause-UC",
"LicenseRef-scancode-other-permissive"
] | permissive | jiajunhuang/4.4BSD-Lite2 | de988da495ee9d167ed4174d8496f8582b0fd2a5 | 8353ed45665ff972b5d9c8f8dfe5ee6440a25a9a | refs/heads/master | 2020-08-02T03:00:01.264557 | 2019-10-31T09:17:48 | 2019-10-31T09:17:48 | 211,215,298 | 0 | 1 | NOASSERTION | 2019-09-27T01:57:11 | 2019-09-27T01:57:11 | null | UTF-8 | C | false | false | 441 | c | /* $Revision: 1.6 $
**
*/
#include <stdio.h>
#include <errno.h>
#include <sys/types.h>
#include "configdata.h"
#include "libinn.h"
#include "clibrary.h"
#include "macros.h"
/*
** Reallocate some memory or call the memory failure handler.
*/
ALIGNPTR
xrealloc(p, i)
char *p;
unsigned int i;
{
POINTER new;
while ((new = realloc((POINTER)p, i)) == NULL)
(*xmemfailure)("remalloc", i);
return CAST(ALIGNPTR, new);
}
| [
"[email protected]"
] | |
48619283036047c5f1f5eba3a24f94b64b2feb46 | 9aebe48109c7058adf08684b77fb3f193a4c6686 | /test/hash/myhash.c | 205e64fb9401bdcbcfce51ed45b98920de376bf6 | [] | no_license | y4bt4/all-in-one | c18a159243dc2c656dadca227aaa346cc2da5d70 | c58041d438b9bf98334c6587e281f25f3849bbeb | refs/heads/master | 2021-01-20T12:00:30.010552 | 2011-04-20T10:07:58 | 2011-04-20T10:07:58 | 1,576,467 | 0 | 0 | null | null | null | null | UTF-8 | C | false | false | 2,970 | c | #include "myhash.h"
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
unsigned calc_hash(const void *key_ptr, int key_len) {
unsigned h = 0x92f7e3b1;
const unsigned char * uc_key_ptr = (const unsigned char *)key_ptr;
while (key_len--) {
h += *uc_key_ptr++;
h += (h << 10);
h ^= (h >> 6);
}
h += (h << 3);
h ^= (h >> 11);
h += (h << 15);
return h;
}
struct myhash* make_hash(int pages,int slots){
struct myhash* h = malloc(sizeof(struct myhash));
int c = 0;
while(pages >>= 1){
c++;
}
if(c < 2){
c = 2;
}
h->pages = 1 << (c + 1);
init_hash(h,slots);
return h;
}
void init_hash(struct myhash* h, int initslots){
int i,j;
char*** ptr = (char***)malloc(h->pages * sizeof(char**));
for(i = 0;i < h->pages; i++){
ptr[i] = (char**)malloc((initslots+1) * sizeof(char*));
for(j = 0; j < initslots; j++){
ptr[i][j] = 0;
}
ptr[i][j] = (char*)-1;
}
h->ptr = ptr;
h->count = 0;
}
void free_hash(struct myhash *h){
int i;
char **ptr;
for(i = 0; i < h->pages; i++){
ptr = h->ptr[i];
while(*ptr && *ptr != (char*)-1){
free(*ptr);
ptr++;
}
free(h->ptr[i]);
}
free(h->ptr);
}
void dump_hash(struct myhash *h,int full){
int i;
char **ptr;
for(i = 0; i < h->pages; i++){
printf("%d\n",i);
ptr = h->ptr[i];
while(*ptr && *ptr != (char*)-1){
if(full){
printf("\t%s: '%s'\n",((struct hash_slot *)*ptr)->key,slot_data(((struct hash_slot *)*ptr)));
}else{
printf("\t%s\n",((struct hash_slot *)*ptr)->key);
}
ptr++;
}
}
printf("\n");
}
int set_hash(struct myhash *h, const char *key_ptr, int key_len, const char *data_ptr, int data_len){
int p, i, size, nsize;
char **ptr, **tmp;
struct hash_slot *slot;
unsigned ch = calc_hash(key_ptr,key_len);
p = ch & (h->pages-1);
ptr = h->ptr[p];
while(*ptr && *ptr != (char*)-1){
ptr++;
}
size = ptr - h->ptr[p];
if(*ptr){
nsize = 2 * (size + 1);
h->ptr[p] = (char**)realloc(h->ptr[p],nsize * sizeof(char*));
ptr = h->ptr[p] + size;
for(i = size; i < nsize; i++){
h->ptr[p][i] = 0;
}
h->ptr[p][i] = (char*)-1;
}
slot = (struct hash_slot*)(*ptr = (char*)malloc(sizeof(struct hash_slot) + key_len + data_len));
slot->ch = ch;
slot->key_len = key_len;
slot->data_len = data_len;
//printf("set: '%s'\n",key_ptr);
memcpy(slot->key,key_ptr,key_len);
//printf("res: '%s'\n",slot->key);
memcpy(slot_data(slot),data_ptr,data_len);
return size;
}
void* get_hash(struct myhash *h, const char *key_ptr, int key_len, int *data_len){
int p;
char **ptr;
struct hash_slot *slot = 0;
unsigned ch = calc_hash(key_ptr,key_len);
p = ch & (h->pages-1);
ptr = h->ptr[p];
while(*ptr && *ptr != (char*)-1){
slot = (struct hash_slot*)*ptr;
if(slot->key_len == key_len && !memcmp(slot->key,key_ptr,key_len)){
*data_len = slot->data_len;
return slot_data(slot);
}
ptr++;
}
return 0;
}
| [
"[email protected]"
] | |
fa596149d16c69154cb61786f56ae1234aceb949 | 976f5e0b583c3f3a87a142187b9a2b2a5ae9cf6f | /source/linux/drivers/thunderbolt/extr_tb.h_tb_route_length.c | 57adde172b9317fa473f0f2a9adef304d398f737 | [] | no_license | isabella232/AnghaBench | 7ba90823cf8c0dd25a803d1688500eec91d1cf4e | 9a5f60cdc907a0475090eef45e5be43392c25132 | refs/heads/master | 2023-04-20T09:05:33.024569 | 2021-05-07T18:36:26 | 2021-05-07T18:36:26 | null | 0 | 0 | null | null | null | null | UTF-8 | C | false | false | 617 | c | #define NULL ((void*)0)
typedef unsigned long size_t; // Customize by platform.
typedef long intptr_t; typedef unsigned long uintptr_t;
typedef long scalar_t__; // Either arithmetic or pointer type.
/* By default, we understand bool (as a convenience). */
typedef int bool;
#define false 0
#define true 1
/* Forward declarations */
/* Type definitions */
typedef int /*<<< orphan*/ u64 ;
/* Variables and functions */
int TB_ROUTE_SHIFT ;
int fls64 (int /*<<< orphan*/ ) ;
__attribute__((used)) static inline int tb_route_length(u64 route)
{
return (fls64(route) + TB_ROUTE_SHIFT - 1) / TB_ROUTE_SHIFT;
} | [
"[email protected]"
] | |
6f9b0d16f4f9831b7754952596a343fdf691dd11 | 892999a2b65eb8510ec0112f20da85072984efb0 | /libembroidery/format-dxf.c | 2b3a67d9292fb295b4da3669d053a7067ae89698 | [
"Zlib"
] | permissive | dyeas/Embroidermodder | 2568f06ebcf86c2497facf426fd9b4a637767208 | f4c0ac8178fe8566a9c4ce040ab80a7dd03688c5 | refs/heads/master | 2020-12-25T07:35:42.973425 | 2013-09-20T23:08:13 | 2013-09-20T23:08:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C | false | false | 16,969 | c | #include "format-dxf.h"
#include <stdio.h>
#include "helpers-misc.h"
/*#include "geom-arc.h" */
/*#include "geom-line.h" */
/* DXF Version Identifiers */
#define DXF_VERSION_R10 "AC1006"
#define DXF_VERSION_R11 "AC1009"
#define DXF_VERSION_R12 "AC1009"
#define DXF_VERSION_R13 "AC1012"
#define DXF_VERSION_R14 "AC1014"
#define DXF_VERSION_R15 "AC1015"
#define DXF_VERSION_R18 "AC1018"
#define DXF_VERSION_R21 "AC1021"
#define DXF_VERSION_R24 "AC1024"
#define DXF_VERSION_2000 "AC1015"
#define DXF_VERSION_2002 "AC1015"
#define DXF_VERSION_2004 "AC1018"
#define DXF_VERSION_2006 "AC1018"
#define DXF_VERSION_2007 "AC1021"
#define DXF_VERSION_2009 "AC1021"
#define DXF_VERSION_2010 "AC1024"
/* Based on the DraftSight color table */
static const unsigned char _dxfColorTable[][3] = {
{ 0, 0, 0 }, /* '0' (BYBLOCK) */
{ 255, 0, 0 }, /* '1' (red) */
{ 255, 255, 0 }, /* '2' (yellow) */
{ 0, 255, 0 }, /* '3' (green) */
{ 0, 255, 255 }, /* '4' (cyan) */
{ 0, 0, 255 }, /* '5' (blue) */
{ 255, 0, 255 }, /* '6' (magenta) */
{ 255, 255, 255 }, /* '7' (white) */
{ 128, 128, 128 }, /* '8' (dark gray) */
{ 192, 192, 192 }, /* '9' (light gray) */
{ 255, 0, 0 }, /* '10' */
{ 255, 127, 127 }, /* '11' */
{ 204, 0, 0 }, /* '12' */
{ 204, 102, 102 }, /* '13' */
{ 153, 0, 0 }, /* '14' */
{ 153, 76, 76 }, /* '15' */
{ 127, 0, 0 }, /* '16' */
{ 127, 63, 63 }, /* '17' */
{ 76, 0, 0 }, /* '18' */
{ 76, 38, 38 }, /* '19' */
{ 255, 63, 0 }, /* '20' */
{ 255, 159, 127 }, /* '21' */
{ 204, 51, 0 }, /* '22' */
{ 204, 127, 102 }, /* '23' */
{ 153, 38, 0 }, /* '24' */
{ 153, 95, 76 }, /* '25' */
{ 127, 31, 0 }, /* '26' */
{ 127, 79, 63 }, /* '27' */
{ 76, 19, 0 }, /* '28' */
{ 76, 47, 38 }, /* '29' */
{ 255, 127, 0 }, /* '30' */
{ 255, 191, 127 }, /* '31' */
{ 204, 102, 0 }, /* '32' */
{ 204, 153, 102 }, /* '33' */
{ 153, 76, 0 }, /* '34' */
{ 153, 114, 76 }, /* '35' */
{ 127, 63, 0 }, /* '36' */
{ 127, 95, 63 }, /* '37' */
{ 76, 38, 0 }, /* '38' */
{ 76, 57, 38 }, /* '39' */
{ 255, 191, 0 }, /* '40' */
{ 255, 223, 127 }, /* '41' */
{ 204, 153, 0 }, /* '42' */
{ 204, 178, 102 }, /* '43' */
{ 153, 114, 0 }, /* '44' */
{ 153, 133, 76 }, /* '45' */
{ 127, 95, 0 }, /* '46' */
{ 127, 111, 63 }, /* '47' */
{ 76, 57, 0 }, /* '48' */
{ 76, 66, 38 }, /* '49' */
{ 255, 255, 0 }, /* '50' */
{ 255, 255, 127 }, /* '51' */
{ 204, 204, 0 }, /* '52' */
{ 204, 204, 102 }, /* '53' */
{ 153, 153, 0 }, /* '54' */
{ 153, 153, 76 }, /* '55' */
{ 127, 127, 0 }, /* '56' */
{ 127, 127, 63 }, /* '57' */
{ 76, 76, 0 }, /* '58' */
{ 76, 76, 38 }, /* '59' */
{ 191, 255, 0 }, /* '60' */
{ 223, 255, 127 }, /* '61' */
{ 153, 204, 0 }, /* '62' */
{ 178, 204, 102 }, /* '63' */
{ 114, 153, 0 }, /* '64' */
{ 133, 153, 76 }, /* '65' */
{ 95, 127, 0 }, /* '66' */
{ 111, 127, 63 }, /* '67' */
{ 57, 76, 0 }, /* '68' */
{ 66, 76, 38 }, /* '69' */
{ 127, 255, 0 }, /* '70' */
{ 191, 255, 127 }, /* '71' */
{ 102, 204, 0 }, /* '72' */
{ 153, 204, 102 }, /* '73' */
{ 76, 153, 0 }, /* '74' */
{ 114, 153, 76 }, /* '75' */
{ 63, 127, 0 }, /* '76' */
{ 95, 127, 63 }, /* '77' */
{ 38, 76, 0 }, /* '78' */
{ 57, 76, 38 }, /* '79' */
{ 63, 255, 0 }, /* '80' */
{ 159, 255, 127 }, /* '81' */
{ 51, 204, 0 }, /* '82' */
{ 127, 204, 102 }, /* '83' */
{ 38, 153, 0 }, /* '84' */
{ 95, 153, 76 }, /* '85' */
{ 31, 127, 0 }, /* '86' */
{ 79, 127, 63 }, /* '87' */
{ 19, 76, 0 }, /* '88' */
{ 47, 76, 38 }, /* '89' */
{ 0, 255, 0 }, /* '90' */
{ 127, 255, 127 }, /* '91' */
{ 0, 204, 0 }, /* '92' */
{ 102, 204, 102 }, /* '93' */
{ 0, 153, 0 }, /* '94' */
{ 76, 153, 76 }, /* '95' */
{ 0, 127, 0 }, /* '96' */
{ 63, 127, 63 }, /* '97' */
{ 0, 76, 0 }, /* '98' */
{ 38, 76, 38 }, /* '99' */
{ 0, 255, 63 }, /* '100' */
{ 127, 255, 159 }, /* '101' */
{ 0, 204, 51 }, /* '102' */
{ 102, 204, 127 }, /* '103' */
{ 0, 153, 38 }, /* '104' */
{ 76, 153, 95 }, /* '105' */
{ 0, 127, 31 }, /* '106' */
{ 63, 127, 79 }, /* '107' */
{ 0, 76, 19 }, /* '108' */
{ 38, 76, 47 }, /* '109' */
{ 0, 255, 127 }, /* '110' */
{ 127, 255, 191 }, /* '111' */
{ 0, 204, 102 }, /* '112' */
{ 102, 204, 153 }, /* '113' */
{ 0, 153, 76 }, /* '114' */
{ 76, 153, 114 }, /* '115' */
{ 0, 127, 63 }, /* '116' */
{ 63, 127, 95 }, /* '117' */
{ 0, 76, 38 }, /* '118' */
{ 38, 76, 57 }, /* '119' */
{ 0, 255, 191 }, /* '120' */
{ 127, 255, 223 }, /* '121' */
{ 0, 204, 153 }, /* '122' */
{ 102, 204, 178 }, /* '123' */
{ 0, 153, 114 }, /* '124' */
{ 76, 153, 133 }, /* '125' */
{ 0, 127, 95 }, /* '126' */
{ 63, 127, 111 }, /* '127' */
{ 0, 76, 57 }, /* '128' */
{ 38, 76, 66 }, /* '129' */
{ 0, 255, 255 }, /* '130' */
{ 127, 255, 255 }, /* '131' */
{ 0, 204, 204 }, /* '132' */
{ 102, 204, 204 }, /* '133' */
{ 0, 153, 153 }, /* '134' */
{ 76, 153, 153 }, /* '135' */
{ 0, 127, 127 }, /* '136' */
{ 63, 127, 127 }, /* '137' */
{ 0, 76, 76 }, /* '138' */
{ 38, 76, 76 }, /* '139' */
{ 0, 191, 255 }, /* '140' */
{ 127, 223, 255 }, /* '141' */
{ 0, 153, 204 }, /* '142' */
{ 102, 178, 204 }, /* '143' */
{ 0, 114, 153 }, /* '144' */
{ 76, 133, 153 }, /* '145' */
{ 0, 95, 127 }, /* '146' */
{ 63, 111, 127 }, /* '147' */
{ 0, 57, 76 }, /* '148' */
{ 38, 66, 76 }, /* '149' */
{ 0, 127, 255 }, /* '150' */
{ 127, 191, 255 }, /* '151' */
{ 0, 102, 204 }, /* '152' */
{ 102, 153, 204 }, /* '153' */
{ 0, 76, 153 }, /* '154' */
{ 76, 114, 153 }, /* '155' */
{ 0, 63, 127 }, /* '156' */
{ 63, 95, 127 }, /* '157' */
{ 0, 38, 76 }, /* '158' */
{ 38, 57, 76 }, /* '159' */
{ 0, 63, 255 }, /* '160' */
{ 127, 159, 255 }, /* '161' */
{ 0, 51, 204 }, /* '162' */
{ 102, 127, 204 }, /* '163' */
{ 0, 38, 153 }, /* '164' */
{ 76, 95, 153 }, /* '165' */
{ 0, 31, 127 }, /* '166' */
{ 63, 79, 127 }, /* '167' */
{ 0, 19, 76 }, /* '168' */
{ 38, 47, 76 }, /* '169' */
{ 0, 0, 255 }, /* '170' */
{ 127, 127, 255 }, /* '171' */
{ 0, 0, 204 }, /* '172' */
{ 102, 102, 204 }, /* '173' */
{ 0, 0, 153 }, /* '174' */
{ 76, 76, 153 }, /* '175' */
{ 0, 0, 127 }, /* '176' */
{ 63, 63, 127 }, /* '177' */
{ 0, 0, 76 }, /* '178' */
{ 38, 38, 76 }, /* '179' */
{ 63, 0, 255 }, /* '180' */
{ 159, 127, 255 }, /* '181' */
{ 51, 0, 204 }, /* '182' */
{ 127, 102, 204 }, /* '183' */
{ 38, 0, 153 }, /* '184' */
{ 95, 76, 153 }, /* '185' */
{ 31, 0, 127 }, /* '186' */
{ 79, 63, 127 }, /* '187' */
{ 19, 0, 76 }, /* '188' */
{ 47, 38, 76 }, /* '189' */
{ 127, 0, 255 }, /* '190' */
{ 191, 127, 255 }, /* '191' */
{ 102, 0, 204 }, /* '192' */
{ 153, 102, 204 }, /* '193' */
{ 76, 0, 153 }, /* '194' */
{ 114, 76, 153 }, /* '195' */
{ 63, 0, 127 }, /* '196' */
{ 95, 63, 127 }, /* '197' */
{ 38, 0, 76 }, /* '198' */
{ 57, 38, 76 }, /* '199' */
{ 191, 0, 255 }, /* '200' */
{ 223, 127, 255 }, /* '201' */
{ 153, 0, 204 }, /* '202' */
{ 178, 102, 204 }, /* '203' */
{ 114, 0, 153 }, /* '204' */
{ 133, 76, 153 }, /* '205' */
{ 95, 0, 127 }, /* '206' */
{ 111, 63, 127 }, /* '207' */
{ 57, 0, 76 }, /* '208' */
{ 66, 38, 76 }, /* '209' */
{ 255, 0, 255 }, /* '210' */
{ 255, 127, 255 }, /* '211' */
{ 204, 0, 204 }, /* '212' */
{ 204, 102, 204 }, /* '213' */
{ 153, 0, 153 }, /* '214' */
{ 153, 76, 153 }, /* '215' */
{ 127, 0, 127 }, /* '216' */
{ 127, 63, 127 }, /* '217' */
{ 76, 0, 76 }, /* '218' */
{ 76, 38, 76 }, /* '219' */
{ 255, 0, 191 }, /* '220' */
{ 255, 127, 223 }, /* '221' */
{ 204, 0, 153 }, /* '222' */
{ 204, 102, 178 }, /* '223' */
{ 153, 0, 114 }, /* '224' */
{ 153, 76, 133 }, /* '225' */
{ 127, 0, 95 }, /* '226' */
{ 127, 63, 111 }, /* '227' */
{ 76, 0, 57 }, /* '228' */
{ 76, 38, 66 }, /* '229' */
{ 255, 0, 127 }, /* '230' */
{ 255, 127, 191 }, /* '231' */
{ 204, 0, 102 }, /* '232' */
{ 204, 102, 153 }, /* '233' */
{ 153, 0, 76 }, /* '234' */
{ 153, 76, 114 }, /* '235' */
{ 127, 0, 63 }, /* '236' */
{ 127, 63, 95 }, /* '237' */
{ 76, 0, 38 }, /* '238' */
{ 76, 38, 57 }, /* '239' */
{ 255, 0, 63 }, /* '240' */
{ 255, 127, 159 }, /* '241' */
{ 204, 0, 51 }, /* '242' */
{ 204, 102, 127 }, /* '243' */
{ 153, 0, 38 }, /* '244' */
{ 153, 76, 95 }, /* '245' */
{ 127, 0, 31 }, /* '246' */
{ 127, 63, 79 }, /* '247' */
{ 76, 0, 19 }, /* '248' */
{ 76, 38, 47 }, /* '249' */
{ 51, 51, 51 }, /* '250' */
{ 91, 91, 91 }, /* '251' */
{ 132, 132, 132 }, /* '252' */
{ 173, 173, 173 }, /* '253' */
{ 214, 214, 214 }, /* '254' */
{ 255, 255, 255 }, /* '255' */
{ 0, 0, 0 } /* '256' (BYLAYER) */
};
char* readLine(FILE* file)
{
char str[255];
fscanf(file, "%s", str);
return lTrim(str, ' ');
}
int readDxf(EmbPattern* pattern, const char* fileName)
{
/*
FILE * file = fopen(fileName, "r");
char *buff;
char *dxfVersion;
char *section;
char *tableName;
char *layerName;
char *entityType;
std::map<string, char> layerMap; //<layerName, colorNum>
std::map<string, int> colorIndexMap; //<layerName, pattern->currentColorIndex>
double bulge, firstX, firstY, x, y, prevX, prevY;
char firstStitch = 1;
char bulgeFlag = 0;
fseek(file, 0L, SEEK_END);
int fileLength = ftell(file);
fseek(file, 0L, SEEK_SET);
while(ftell(file) < fileLength)
{
buff = readLine(file);
if((strcmp(buff,"HEADER") == 0) || (strcmp(buff, "TABLES") == 0) || (strcmp(buff, "ENTITIES") == 0))
{
section = buff;
}
if(strcmp(buff, "ENDSEC") == 0)
{
section = NULL;
}
if((strcmp(buff, "LWPOLYLINE") == 0) || (strcmp(buff, "CIRCLE") == 0))
{
entityType = buff;
}
if(strcmp(buff, "EOF") == 0)
{
AddStitchAbs(pattern, 0.0, 0.0, END, 1);
}
if(strcmp(section, "HEADER") == 0)
{
if(strcmp(buff, "$ACADVER") == 0)
{
buff = readLine(file);
dxfVersion = readLine(file);
//TODO: Allow these versions when POLYLINE is handled.
if((strcmp(dxfVersion, DXF_VERSION_R10) == 0)
|| (strcmp(dxfVersion, DXF_VERSION_R11) == 0)
|| (strcmp(dxfVersion, DXF_VERSION_R12) == 0)
|| (strcmp(dxfVersion, DXF_VERSION_R13) == 0)
|| (strcmp(dxfVersion, DXF_VERSION_R14) == 0))
return 0;
}
}
else if (strcmp(section,"TABLES") == 0)
{
if(strcmp(buff,"ENDTAB") == 0)
{
tableName = NULL;
}
if(tableName == NULL)
{
if(strcmp(buff,"2") == 0) //Table Name
{
tableName = readLine(file);
}
}
else if (strcmp(tableName, "LAYER") == 0)
{
//Common Group Codes for Tables
if(strcmp(buff,"5") == 0) //Handle
{
buff = readLine(file);
continue;
}
else if(strcmp(buff,"330") == 0) //Soft Pointer
{
buff = readLine(file);
continue;
}
else if(strcmp(buff,"100") == 0) //Subclass Marker
{
buff = readLine(file);
continue;
}
else if(strcmp(buff,"70") == 0) //Number of Entries in Table
{
buff = readLine(file);
continue;
}
//The meaty stuff
else if(strcmp(buff,"2") == 0) //Layer Name
{
layerName = readLine(file);
}
else if(strcmp(buff,"62") == 0) //Color Number
{
buff = readLine(file);
unsigned char colorNum = atoi(buff);
layerMap[layerName] = colorNum;
colorIndexMap[layerName] = (pattern_AddThread(pattern,
_dxfColorTable[colorNum][0],
_dxfColorTable[colorNum][1],
_dxfColorTable[colorNum][2], layerName,
buff) - 1);
layerName = NULL;
}
}
}
else if(strcmp(section,"ENTITIES") == 0)
{
//Common Group Codes for Entities
if(strcmp(buff, "5") == 0) //Handle
{
buff = readLine(file);
continue;
}
else if(strcmp(buff, "330") == 0) //Soft Pointer
{
buff = readLine(file);
continue;
}
else if(strcmp(buff, "100") == 0) //Subclass Marker
{
buff = readLine(file);
continue;
}
else if(strcmp(buff, "8") == 0) //Layer Name
{
buff = readLine(file);
embPattern_changeColor(pattern, colorIndexMap[buff]);
continue;
}
if(strcmp(entityType,"LWPOLYLINE") == 0)
{
//The not so important group codes
if(strcmp(buff, "90") == 0) //Vertices
{
buff = readLine(file);
continue;
}
else if(strcmp(buff,"70") == 0) //Polyline Flag
{
buff = readLine(file);
continue;
}
//TODO: Try to use the widths at some point
else if(strcmp(buff,"40") == 0) //Starting Width
{
buff = readLine(file);
continue;
}
else if(strcmp(buff,"41") == 0) //Ending Width
{
buff = readLine(file);
continue;
}
else if(strcmp(buff,"43") == 0) //Constant Width
{
buff = readLine(file);
continue;
}
//The meaty stuff
else if(strcmp(buff,"42") == 0) //Bulge
{
buff = readLine(file);
bulge = atof(buff);
bulgeFlag = 1;
}
else if(strcmp(buff,"10") == 0) //X
{
buff = readLine(file);
x = atof(buff);
}
else if(strcmp(buff,"20") == 0) //Y
{
buff = readLine(file);
y = atof(buff);
if(bulgeFlag)
{
bulgeFlag = 0;
getArcDataFromBulge(pattern, bulge, prevX, prevY, x, y);
if(firstStitch)
{
AddStitchAbs(pattern, x, y, TRIM, 1);
}
AddStitchAbs(pattern, x, y, ARC, 1);
}
else
{
if(firstStitch) AddStitchAbs(pattern, x, y, TRIM, 1);
else AddStitchAbs(pattern, x, y, NORMAL, 1);
}
prevX = x;
prevY = y;
if(firstStitch)
{
firstX = x;
firstY = y;
firstStitch = 0;
}
}
else if(strcmp(buff,"0") == 0)
{
entityType = NULL;
firstStitch = 1;
if(bulgeFlag)
{
bulgeFlag = 0;
getArcDataFromBulge(pattern, bulge, prevX, prevY, firstX, firstY);
AddStitchAbs(pattern, prevX, prevY, ARC, 1);
}
else
{
AddStitchAbs(pattern, firstX, firstY, NORMAL, 1);
}
}
}
} // end ENTITIES section
} // end while loop
fclose(file);
return 1;
*/
return 0; /*TODO: remove this. Port ReadDxf to C */
}
int writeDxf(EmbPattern* pattern, const char* fileName)
{
return 0; /*TODO: finish writeDxf */
}
/* kate: bom off; indent-mode cstyle; indent-width 4; replace-trailing-space-save on; */
| [
"[email protected]"
] | |
c88759defd80c164bfecbc867519f954b31670e5 | 54125f637e21140bdf8889da618d75ccf4a735e5 | /mfs/examples/mfs_ftp/USB_File.h | 5183720d9930dd33e84d5f3e4a66baa076fa1322 | [] | no_license | gxliu/MQX_3.8.1 | 41d0dee466cf80e9f406f7d9cefd39f592ddc9fb | 5bff1cb96afa8ee8245819a81563ae2145a3b3a4 | refs/heads/master | 2021-01-15T22:38:53.417127 | 2013-05-20T12:35:57 | 2013-05-20T12:35:57 | null | 0 | 0 | null | null | null | null | UTF-8 | C | false | false | 2,139 | h | #ifndef __usb_file_h__
#define __usb_file_h__
/**HEADER********************************************************************
*
* Copyright (c) 2008 Freescale Semiconductor;
* All Rights Reserved
*
* Copyright (c) 2004-2008 Embedded Access Inc.;
* All Rights Reserved
*
***************************************************************************
*
* THIS SOFTWARE IS PROVIDED BY FREESCALE "AS IS" AND ANY EXPRESSED OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL FREESCALE OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*
**************************************************************************
*
* $FileName: USB_File.h$
* $Version : 3.8.4.1$
* $Date : Feb-13-2012$
*
* Comments:
*
* This file contains the Test specific data structures and defines
*
*END************************************************************************/
typedef struct {
MQX_FILE_PTR DEV_FD_PTR;
MQX_FILE_PTR PM_FD_PTR;
MQX_FILE_PTR FS_FD_PTR;
char_ptr DEV_NAME;
char_ptr PM_NAME;
char_ptr FS_NAME;
} USB_FILESYSTEM_STRUCT, * USB_FILESYSTEM_STRUCT_PTR;
#ifdef __cplusplus
extern "C" {
#endif
extern pointer usb_filesystem_install(
pointer usb_handle,
char_ptr block_device_name,
char_ptr partition_manager_name,
char_ptr file_system_name );
extern void usb_filesystem_uninstall( USB_FILESYSTEM_STRUCT_PTR usb_fs_ptr);
extern MQX_FILE_PTR usb_filesystem_handle( USB_FILESYSTEM_STRUCT_PTR usb_fs_ptr);
#ifdef __cplusplus
}
#endif
#endif
/* EOF */
| [
"[email protected]"
] | |
841d340ce8e1a262b181d1e3fafecbfa03a46261 | d5c68582bfde399806fcbbc3f6898bcfdc2c7969 | /Part I/ft_strncmp.c | 5d7c82c14adc63f8bacd6c66a2f67be174c84fa0 | [] | no_license | MatheusCoscia/42Libft_Commented | b7a99b16f3bc16dd9c2f91a2f4e51e585d263355 | f49e613d28760a25efd20499257ca0f8a01e8ac0 | refs/heads/main | 2023-07-31T17:46:43.451308 | 2021-09-15T20:13:41 | 2021-09-15T20:13:41 | 402,950,683 | 0 | 1 | null | null | null | null | UTF-8 | C | false | false | 1,854 | c | /* ************************************************************ */
/* */
/* ╓▀▀▀▀▀▀▄ ::: :::::::: */
/* █▀ ▐ :+: :+: :+: */
/* █ ▀ ▓█ +:+ +:+ +:+ */
/* █ █▓▓▓▓█ +#+ +:+ +#+ */
/* ▄▄ ▄▄▄███████─▄▀█▀▀ +#+#+#+#+#+ +#+ */
/* █ ███████████▄██ ██ #+# #+# */
/* █ █▀▀ ██████████▌ ### ########.fr */
/* █ ▀▄▄ ▀████████▌ */
/* ▀█ ▀ ▄▄▄████████▌ 42cursus | MCoscia | matrodri */
/* ▀▀ ▄▄▄▄▄▄▄▄▄█▀ quack quack | vila pescopata */
/* */
/* ************************************************************ */
/*
** RETORNAR A DIFERENCA ENTRE DUAS STRING DENTRO DE SEUS PRIMEIROS 'n' CARATERES
*/
#include "libft.h"
int ft_strncmp(const char *s1, const char *s2, size_t n)
{
size_t i;
i = 0;
/* enquanto 'n' for diferente de 0 e nossa string 1 for diferente da string 2 iremos permanecer no loop */
while (n--)
{
if (s1[i] != s2[i] || s1[i] == '\0' || s2[i] == '\0')
/* iremos retornar a diferenca entre s1 e s2 ~#consultar valores abaixo */
return ((unsigned char) s1[i] - (unsigned char) s2[i]);
i++;
}
return (0);
}
/*
os valores retornados devarao ser:
se s1 > s2 | retornaremos um valor positivo
se s1 < s2 | retornaremos um valor negativo
se s1 = s2 | retornaremos 0
*/
| [
"[email protected]"
] | |
657cade5ed926a8f6a0e63411c0ec3e0f7363532 | 3d509317223ed258354261f17e01c2a968f3c3ef | /spinpaem7/spin7.c | 0ad49dad592b4d5c0d00814d6bc1a6f8f0f59fb3 | [] | no_license | pavolbauer/paem | 54c01954d256f56de20d9f0c4dfe6232ff398454 | e7bb04fe052f6ceae6abb546815d10ae9f960be2 | refs/heads/master | 2020-04-11T00:40:51.969255 | 2017-05-23T10:58:51 | 2017-05-23T10:58:51 | 20,854,245 | 0 | 0 | null | null | null | null | UTF-8 | C | false | false | 609 | c | /* Propensity file for test "spin2"
* P. Bauer 2012-03-28
*/
#include <stdlib.h>
#include "propensities.h"
#define NR 2
/* Reaction propensities. */
double rFun1(const int *x, double t, double vol, const double *data, int sd)
{
return 2*x[0]*(x[0]-1)/vol;
}
double rFun2(const int *x, double t, double vol, const double *data, int sd)
{
return 2*x[1]*(x[1]-1)/vol;
}
PropensityFun *ALLOC_propensities(void)
{
PropensityFun *ptr = (PropensityFun *)malloc(sizeof(PropensityFun)*NR);
ptr[0]=rFun1;
ptr[1]=rFun2;
return ptr;
}
void FREE_propensities(PropensityFun* ptr)
{
free(ptr);
} | [
"[email protected]"
] | |
44793bc3cb1e76b0203b8a5c0fd3514382767812 | 30e9a2863deef9763a338a5ecc06404a14c7641e | /c/arm_neon_intrinsic/rgb_deinterleave/rgb_deinterleave.c | 35a33c5c28be6f549da098b0e70d492c5154314c | [
"Apache-2.0"
] | permissive | ryoma-jp/samples | 1311b7c45da9aaccecd76787945bf4106257323e | 6437a4bb7952bd6a242c249092e10df01e04a55f | refs/heads/master | 2023-07-07T02:47:00.042632 | 2023-07-01T08:12:32 | 2023-07-01T08:12:32 | 210,209,918 | 0 | 0 | null | null | null | null | UTF-8 | C | false | false | 1,824 | c | /**
* @file rgb_deinterleave.c
* @brief RGBインターリーブ画像データからRGBピクセル値を取得する
*/
#include <arm_neon.h>
#include "common.h"
#include "rgb_deinterleave.h"
/**
* @brief RGBインターリーブ画像データからRGBピクセル値を取得する(C言語版)
* @param src 入力RGBデータ
* @param src_len 入力RGBデータのデータサイズ[byte]
* @param dst RGBピクセル値を格納するバッファ(dst[R, G, B])
* @return int 0固定
* @details srcからRGBピクセル値を取得し,dstへ格納する
*/
int rgb_deinterleave_c(unsigned char* src, int src_len, unsigned char* dst[3])
{
MY_PRINT(MY_PRINT_LVL_INFO, "rgb_deinterleave_c\n");
unsigned char* r;
unsigned char* g;
unsigned char* b;
int i;
r = dst[0];
g = dst[1];
b = dst[2];
for (i = 0; i < (src_len) / 3; i++) {
r[i] = src[3*i];
g[i] = src[3*i+1];
b[i] = src[3*i+2];
}
return 0;
}
/**
* @brief RGBインターリーブ画像データからRGBピクセル値を取得する(neon版)
* @param src 入力RGBデータ
* @param src_len 入力RGBデータのデータサイズ[byte]
* @param dst RGBピクセル値を格納するバッファ(dst[R, G, B])
* @return int 0固定
* @details srcからRGBピクセル値を取得し,dstへ格納する
*/
int rgb_deinterleave_neon(unsigned char* src, int src_len, unsigned char* dst[3])
{
MY_PRINT(MY_PRINT_LVL_INFO, "rgb_deinterleave_neon\n");
unsigned char* r;
unsigned char* g;
unsigned char* b;
uint8x16x3_t intlv_rgb;
int num8x16 = src_len / 3 / 16 + 1;
int i;
r = dst[0];
g = dst[1];
b = dst[2];
for (i=0; i < num8x16; i++) {
intlv_rgb = vld3q_u8(src+3*16*i);
vst1q_u8(r+16*i, intlv_rgb.val[0]);
vst1q_u8(g+16*i, intlv_rgb.val[1]);
vst1q_u8(b+16*i, intlv_rgb.val[2]);
}
return 0;
}
| [
"[email protected]"
] | |
990a5af8717a7101f650be459d79c9a04dfeb1c5 | b1d500a451cd9852089bf3d97e829df069daa9c8 | /Images/MC/ToyRadialFieldScan/Config_2/FieldFit_NSUBRUN_125_NEXP_0.C | 808de859481827a52c534876446738d85a0e42a0 | [] | no_license | sam-grant/EDM | 486ea029bf766c968a3c7b41198ffcf9bc3c9b8a | 525e41de5f675c39014488c79144f47562910736 | refs/heads/master | 2022-10-30T22:35:42.979799 | 2022-10-19T18:44:54 | 2022-10-19T18:44:54 | 296,421,806 | 0 | 1 | null | null | null | null | UTF-8 | C | false | false | 5,307 | c | void FieldFit_NSUBRUN_125_NEXP_0()
{
//=========Macro generated from canvas: c/c
//========= (Fri Oct 16 07:49:26 2020) by ROOT version 6.22/02
TCanvas *c = new TCanvas("c", "c",0,0,800,600);
c->SetHighLightColor(2);
c->Range(-45,-0.200897,45,0.1511737);
c->SetFillColor(0);
c->SetBorderMode(0);
c->SetBorderSize(2);
c->SetFrameBorderMode(0);
c->SetFrameBorderMode(0);
Double_t Graph0_fx1057[4] = {
-30,
-10,
10,
30};
Double_t Graph0_fy1057[4] = {
0.0878271,
0.01173497,
-0.0791649,
-0.1375504};
Double_t Graph0_fex1057[4] = {
0,
0,
0,
0};
Double_t Graph0_fey1057[4] = {
0.004668138,
0.004668138,
0.004668138,
0.004668138};
TGraphErrors *gre = new TGraphErrors(4,Graph0_fx1057,Graph0_fy1057,Graph0_fex1057,Graph0_fey1057);
gre->SetName("Graph0");
gre->SetTitle("Sub-runs 125");
gre->SetFillStyle(1000);
gre->SetMarkerStyle(20);
TH1F *Graph_Graph01057 = new TH1F("Graph_Graph01057","Sub-runs 125",100,-36,36);
Graph_Graph01057->SetMinimum(-0.1656899);
Graph_Graph01057->SetMaximum(0.1159666);
Graph_Graph01057->SetDirectory(0);
Graph_Graph01057->SetStats(0);
Int_t ci; // for color index setting
TColor *color; // for color definition with alpha
ci = TColor::GetColor("#000099");
Graph_Graph01057->SetLineColor(ci);
Graph_Graph01057->GetXaxis()->SetTitle("Applied B_{r} [ppm]");
Graph_Graph01057->GetXaxis()->CenterTitle(true);
Graph_Graph01057->GetXaxis()->SetLabelFont(42);
Graph_Graph01057->GetXaxis()->SetTitleSize(0.04);
Graph_Graph01057->GetXaxis()->SetTitleOffset(1.1);
Graph_Graph01057->GetXaxis()->SetTitleFont(42);
Graph_Graph01057->GetYaxis()->SetTitle("#LTy#GT / QHV [mm/kV]");
Graph_Graph01057->GetYaxis()->CenterTitle(true);
Graph_Graph01057->GetYaxis()->SetNdivisions(4000510);
Graph_Graph01057->GetYaxis()->SetLabelFont(42);
Graph_Graph01057->GetYaxis()->SetTitleSize(0.04);
Graph_Graph01057->GetYaxis()->SetTitleOffset(1.2);
Graph_Graph01057->GetYaxis()->SetTitleFont(42);
Graph_Graph01057->GetZaxis()->SetLabelFont(42);
Graph_Graph01057->GetZaxis()->SetTitleOffset(1);
Graph_Graph01057->GetZaxis()->SetTitleFont(42);
gre->SetHistogram(Graph_Graph01057);
TF1 *mainFit1058 = new TF1("mainFit","[0]+[1]*x",-36,36, TF1::EAddToList::kNo);
mainFit1058->SetFillColor(19);
mainFit1058->SetFillStyle(0);
ci = TColor::GetColor("#ff0000");
mainFit1058->SetLineColor(ci);
mainFit1058->SetLineWidth(2);
mainFit1058->SetChisquare(8.73505);
mainFit1058->SetNDF(2);
mainFit1058->GetXaxis()->SetLabelFont(42);
mainFit1058->GetXaxis()->SetTitleOffset(1);
mainFit1058->GetXaxis()->SetTitleFont(42);
mainFit1058->GetYaxis()->SetLabelFont(42);
mainFit1058->GetYaxis()->SetTitleFont(42);
mainFit1058->SetParameter(0,-0.02928832);
mainFit1058->SetParError(0,0.002334069);
mainFit1058->SetParLimits(0,0,0);
mainFit1058->SetParameter(1,-0.003835162);
mainFit1058->SetParError(1,0.0001043827);
mainFit1058->SetParLimits(1,0,0);
mainFit1058->SetParent(gre);
gre->GetListOfFunctions()->Add(mainFit1058);
gre->Draw("ap");
TPaveText *pt = new TPaveText(0.69,0.68,0.89,0.89,"brNDC");
pt->SetFillColor(0);
pt->SetTextAlign(33);
pt->SetTextFont(44);
pt->SetTextSize(26);
TText *pt_LaTex = pt->AddText(" 4.37");
pt_LaTex = pt->AddText("#minus0.00384#pm0.000104");
pt_LaTex = pt->AddText("#minus0.0293#pm0.00233");
pt_LaTex = pt->AddText("#minus7.64#pm0.643");
pt->Draw();
pt = new TPaveText(0.3,0.69,0.62,0.88,"brNDC");
pt->SetFillColor(0);
pt->SetTextAlign(13);
pt->SetTextFont(44);
pt->SetTextSize(26);
pt_LaTex = pt->AddText("#chi^{2}/ndf");
pt_LaTex = pt->AddText("Gradient [mm/kV#upointppm]");
pt_LaTex = pt->AddText("Y-intercept [mm/kV]");
pt_LaTex = pt->AddText("Background B_{r} [ppm]");
pt->Draw();
TLine *line = new TLine(-36,0,-7.636787,0);
line->SetLineStyle(2);
line->SetLineWidth(2);
line->Draw();
line = new TLine(-7.636787,-0.1656899,-7.636787,0);
line->SetLineStyle(2);
line->SetLineWidth(2);
line->Draw();
TF1 *mainFit1059 = new TF1("mainFit","[0]+[1]*x",-36,36, TF1::EAddToList::kNo);
mainFit1059->SetFillColor(19);
mainFit1059->SetFillStyle(0);
ci = TColor::GetColor("#ff0000");
mainFit1059->SetLineColor(ci);
mainFit1059->SetLineWidth(2);
mainFit1059->SetChisquare(8.73505);
mainFit1059->SetNDF(2);
mainFit1059->GetXaxis()->SetLabelFont(42);
mainFit1059->GetXaxis()->SetTitleOffset(1);
mainFit1059->GetXaxis()->SetTitleFont(42);
mainFit1059->GetYaxis()->SetLabelFont(42);
mainFit1059->GetYaxis()->SetTitleFont(42);
mainFit1059->SetParameter(0,-0.02928832);
mainFit1059->SetParError(0,0.002334069);
mainFit1059->SetParLimits(0,0,0);
mainFit1059->SetParameter(1,-0.003835162);
mainFit1059->SetParError(1,0.0001043827);
mainFit1059->SetParLimits(1,0,0);
mainFit1059->Draw("same");
pt = new TPaveText(0.3750503,0.94,0.6249497,0.995,"blNDC");
pt->SetName("title");
pt->SetBorderSize(0);
pt->SetFillColor(0);
pt->SetFillStyle(0);
pt->SetTextFont(42);
pt_LaTex = pt->AddText("Sub-runs 125");
pt->Draw();
c->Modified();
c->cd();
c->SetSelected(c);
}
| [
"[email protected]"
] | |
418256858c047d6c601736d1d26b2af7fad6828e | de9b2174f4bb4dc878ce64ee08a2405dd8922825 | /Interrupt.c | b1f4cde40d736f45f39be1029c2918fb4773a64b | [] | no_license | hoantien/F28355_FW | 3331826213c5df784c6c76a799d6c1585277acef | 7f4286249695765a00a9b7b9d8298ab4c2cd39a4 | refs/heads/master | 2020-12-25T17:24:05.205575 | 2016-05-23T15:49:25 | 2016-05-23T15:49:25 | 59,495,485 | 0 | 0 | null | null | null | null | UTF-8 | C | false | false | 1,154 | c | /*******************************************************************************
* Copyright (c) 2015, Luong Hoan Tien
* This source code is used for the Tien's project in master program at
* University of Technology and Education HCM city. All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are strictly prohibited without prior permission
* of Mr.Luong Hoan Tien.
*
* @file Interrupt.c
* @author Luong Hoan Tien
* @version V2.0
* @date May-2015
* @brief This file contains expand of interrupt
*
******************************************************************************/
#include "Interrupt.h"
extern Uint8 flag_irq;
interrupt void cpu_timer0_isr(void)
{
CpuTimer0.InterruptCount++;
PieCtrlRegs.PIEACK.all = PIEACK_GROUP1;
if (20000 < CpuTimer0.InterruptCount)
{
CpuTimer0.InterruptCount = 0;
}
}
interrupt void epwm1_isr(void)
{
EPwm1Regs.ETCLR.bit.INT = 1;
PieCtrlRegs.PIEACK.all = PIEACK_GROUP3;
flag_irq =1;
}
interrupt void epwm2_isr(void)
{
EPwm2Regs.ETCLR.bit.INT = 1;
PieCtrlRegs.PIEACK.all = PIEACK_GROUP3;
flag_irq =1;
}
| [
"[email protected]"
] | |
ac0b0e9cd7c3550d1bcb70d125100ef1aff5675f | 35691c30af897b30e5bd366bed5e740802901c12 | /Book/Finding a number in an array.c | 96c1cbc4c8c254c6dbc5db2e7fd5190bc4389742 | [] | no_license | asiffmahmudd/C-Programming-Language | 18ce8ca337a3b3131ea9276830fcc4691a6f002d | 339db7c4e2aa1ad4d669e64b43a4aa229e124e1c | refs/heads/master | 2020-06-12T12:46:35.283045 | 2019-06-28T16:28:02 | 2019-06-28T16:28:02 | 194,303,384 | 0 | 0 | null | null | null | null | UTF-8 | C | false | false | 778 | c | #include <stdio.h>
int main()
{
int ara[] = {1, 4, 6, 8, 9, 11, 14, 15, 20, 25, 33, 83, 87, 97, 99, 100};
int low_index = 0;
int high_index = 15;
int mid_index;
int num = 97;
while (low_index <= high_index)
{
mid_index =(low_index + high_index)/2;
if(num == ara[mid_index])
{
break;
}
else if(num < ara[mid_index])
{
high_index = mid_index - 1;
}
else
{
low_index = mid_index + 1;
}
}
if(low_index > high_index)
{
printf("%d is not in the array\n", num);
}
else
{
printf("%d is the %dth number of the array\n", ara[mid_index], mid_index);
}
return 0;
}
| [
"[email protected]"
] | |
1eafdea483896638c50f1e79e4dccb948d01033d | 689386250bee426460cd6e7b4ec199f555aede04 | /talkWithAppServer.c | 5149f9e5e6284731b30c47cef5df01b1c93546bb | [] | no_license | jiabing1030/environmentMonitorSystem | e955431778f223516d45c7bead98c166ccb20dea | 1bece0ef6a991d8a76d6b94d0dc312430db24d6c | refs/heads/master | 2021-04-09T11:29:42.835552 | 2018-03-12T13:20:44 | 2018-03-12T13:20:44 | 125,448,827 | 0 | 0 | null | null | null | null | UTF-8 | C | false | false | 2,582 | c | #include <talkWithAppServer.h>
#include <myglobal.h>
#include <unistd.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <pthread.h>
#include <strings.h>
#include <stdio.h>
void payloadHandler(int packetType,unsigned char *data,int length);
static int listen_fd;
static void (*storeControlData)(unsigned char *data);
static void (*sendControlData)(unsigned char *data);
int talkwithAppServerInit(void (*dataCenterCB)(unsigned char *data),void (*sensorNetCB)(unsigned char *data))
{
struct sockaddr_in listenAddr;
int socksize,ret;
int i=1;
socksize=sizeof(struct sockaddr);
bzero(&listenAddr,sizeof(listenAddr));
listenAddr.sin_family=AF_INET;
listenAddr.sin_port=htons(SERVER_PORT);
listenAddr.sin_addr.s_addr=INADDR_ANY;
listen_fd=socket(AF_INET,SOCK_STREAM,0);
setsockopt( listen_fd,SOL_SOCKET,SO_REUSEADDR,&i,sizeof(i));
ret=bind( listen_fd,(struct sockaddr*)&listenAddr,socksize);
if(ret==0)
printf("Bind successfully:%d\n",SERVER_PORT);
ret=listen( listen_fd,8);
if(ret==0)
printf("Listen successfully!\n");
storeControlData=dataCenterCB;
sendControlData=sensorNetCB;
return 0;
}
void talkWithAppServerStart(void)
{
int count;
socklen_t socksize=sizeof(struct sockaddr);
while(1)
{
int comm_fd;
struct sockaddr_in client_addr;
if((comm_fd=accept(listen_fd,(struct sockaddr*)&client_addr,&socksize))>=0)
{
char ipstr[16];
unsigned char buf[100];
int length;
int i;
inet_ntop(AF_INET,&client_addr.sin_addr.s_addr,ipstr,16);
printf("A new connection come on:%s\n",ipstr);
//获取数据包起始字节0xfc
while(1)
{
count=read(comm_fd,buf,1);
if(count<=0)
{
perror("Net error:");
break;
}
if(buf[0]==0xfc)
{
read(comm_fd,buf,1);
read(comm_fd,buf+1,1);
length=buf[1];
i=2;
for(;length>0;length--)
{
count=read(comm_fd,buf+i,length);
i+=count;
length-=count;
}
storeControlData(buf);
sendControlData(buf);
}
}
}
}
}
void talkWithAppServerExit(void)
{
close( listen_fd);
}
| [
"[email protected]"
] | |
1b135bc9d92a42dd811f3c863dbea5897a312a58 | 3b96465faaffe43ca416189e426be7f306112513 | /external/libzip/lib/zip_crypto_mbedtls.h | 738195105d35da2c2db27d207d06748179fe4b9e | [
"MIT",
"BSD-3-Clause"
] | permissive | danilolc/pk2 | 4e00290178af55a7ead005c081364e62622df922 | b1c5597a0af78e88e1519eae7d8f042d88041d38 | refs/heads/main | 2023-08-17T10:32:43.329231 | 2023-05-08T16:15:26 | 2023-05-08T16:15:26 | 89,756,665 | 76 | 27 | MIT | 2023-05-17T21:49:31 | 2017-04-29T01:34:36 | C++ | UTF-8 | C | false | false | 2,735 | h | /*
zip_crypto_mbedtls.h -- definitions for mbedtls wrapper
Copyright (C) 2018-2019 Dieter Baron and Thomas Klausner
This file is part of libzip, a library to manipulate ZIP archives.
The authors can be contacted at <[email protected]>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution.
3. The names of the authors may not be used to endorse or promote
products derived from this software without specific prior
written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS
OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef HAD_ZIP_CRYPTO_MBEDTLS_H
#define HAD_ZIP_CRYPTO_MBEDTLS_H
#define HAVE_SECURE_RANDOM
#include <mbedtls/aes.h>
#include <mbedtls/md.h>
#define _zip_crypto_aes_t mbedtls_aes_context
#define _zip_crypto_hmac_t mbedtls_md_context_t
_zip_crypto_aes_t *_zip_crypto_aes_new(const zip_uint8_t *key, zip_uint16_t key_size, zip_error_t *error);
#define _zip_crypto_aes_encrypt_block(aes, in, out) (mbedtls_aes_crypt_ecb((aes), MBEDTLS_AES_ENCRYPT, (in), (out)) == 0)
void _zip_crypto_aes_free(_zip_crypto_aes_t *aes);
_zip_crypto_hmac_t *_zip_crypto_hmac_new(const zip_uint8_t *secret, zip_uint64_t secret_length, zip_error_t *error);
#define _zip_crypto_hmac(hmac, data, length) (mbedtls_md_hmac_update((hmac), (data), (length)) == 0)
#define _zip_crypto_hmac_output(hmac, data) (mbedtls_md_hmac_finish((hmac), (data)) == 0)
void _zip_crypto_hmac_free(_zip_crypto_hmac_t *hmac);
bool _zip_crypto_pbkdf2(const zip_uint8_t *key, zip_uint64_t key_length, const zip_uint8_t *salt, zip_uint16_t salt_length, int iterations, zip_uint8_t *output, zip_uint64_t output_length);
#endif /* HAD_ZIP_CRYPTO_MBEDTLS_H */
| [
"[email protected]"
] | |
fe264fc2b0358ba8fa6bb01843f12cc073cc0e3f | bbddd5ff9a18412142f0d7d30b131a28dee876d4 | /driver/lcd_1602/lcd.h | e3c3b245793a885c2d9aba93f3702474007a1fec | [] | no_license | HungBX1997/MOCK_Project | c60adf57833dd94701978ed2db77203e3db4250c | ca816e88bb4c76cc24c27981ab24be727d160cd6 | refs/heads/main | 2023-03-24T07:04:26.559518 | 2021-03-23T16:08:56 | 2021-03-23T16:08:56 | 350,775,408 | 0 | 0 | null | null | null | null | UTF-8 | C | false | false | 502 | h | #ifndef __LCD_H_
#define __LCD_H_
#include <stdint.h>
#define ADD_PCF8574 (0x27)
void DRV_Delay(uint32_t miliSecond);
void LCD_Send_CMD(char cmd);
void LCD_Init();
void LCD_Send_Data(char data);
void LCD_Send_String(char *str);
void LCD_goto_XY (int row, int col);
void LCD_Main_Screen();
void LCD_Search_Screen();
void LCD_Setup_Screen();
void LCD_RunFreqSelected_Screen(float freq);
void LCD_SelectChannelScreen(float freq);
void LCD_tranDataFreq(float freq);
#endif /*__LCD_H_*/ | [
"[email protected]"
] | |
3ef066497d04c44aa8bf18f569cfd8fccd8eb4e8 | 9e12afb01d76b357abcc781f78c9af2a8c9628e6 | /0x1A-hash_tables/3-hash_table_set.c | 21d8fa0a053cdcff0eaebaa3321f37bdf6f8c7e6 | [] | no_license | fabio-gz/holbertonschool-low_level_programming | f7d302bfbfb27bf20d6cefdb03dfd7777febde7f | 137077c4abab9120a43e81e3ea4a63e44b050366 | refs/heads/master | 2020-07-28T07:17:42.895310 | 2020-04-15T23:03:26 | 2020-04-15T23:03:26 | 209,348,796 | 0 | 0 | null | null | null | null | UTF-8 | C | false | false | 943 | c | #include "hash_tables.h"
/**
*hash_table_set - adds an element to the hash table
*@ht: hash table to add or update
*@key: key
*@value: value for the key
*Return: 1 for success, 0 otherwise
*/
int hash_table_set(hash_table_t *ht, const char *key, const char *value)
{
hash_node_t *new, *nde;
unsigned long int index;
if (ht == NULL || key == NULL || ht->array == NULL)
return (0);
index = key_index((const unsigned char *)key, ht->size);
nde = ht->array[index];
while (nde)
{
if (!strcmp(nde->key, key))
{
free(nde->value);
nde->value = strdup(value);
return (1);
}
nde = nde->next;
}
new = malloc(sizeof(hash_node_t));
if (new == NULL)
return (0);
new->key = strdup(key);
if (new->key == NULL)
{
return (free(new->key), free(new), 0);
}
new->value = strdup(value);
if (ht->array[index] != NULL)
new->next = ht->array[index];
else
new->next = NULL;
ht->array[index] = new;
return (1);
}
| [
"[email protected]"
] | |
e5f6e494d9edb184822e15f1820acdf9ccb6aae8 | f325d7aa3fe26918a90bbad40c38a0ea38921593 | /Temp/il2cppOutput/il2cppOutput/mscorlib_System_Runtime_Remoting_Contexts_CrossCon2085016836MethodDeclarations.h | 1e0099fb1e12a6a340a5cc63c42a1ebcc301e578 | [] | no_license | zenithght/FacebookTwitterTest | 1776f54719f6841beb499437c80cef68e3707cdb | 5b3b71a50d99cbfb6352e598bd0a1ccd2597e000 | refs/heads/master | 2021-01-21T11:08:00.998606 | 2016-04-15T03:02:10 | 2016-04-15T03:02:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C | false | false | 1,776 | h | #pragma once
#include "il2cpp-config.h"
#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif
#include <stdint.h>
#include <assert.h>
#include <exception>
// System.Runtime.Remoting.Contexts.CrossContextDelegate
struct CrossContextDelegate_t2085016836_0;
// System.Object
struct Object_t;
// System.IAsyncResult
struct IAsyncResult_t_2075007983_0;
// System.AsyncCallback
struct AsyncCallback_t_626615168_0;
#include "codegen/il2cpp-codegen.h"
#include "mscorlib_System_IntPtr1759419328.h"
// System.Void System.Runtime.Remoting.Contexts.CrossContextDelegate::.ctor(System.Object,System.IntPtr)
extern "C" void CrossContextDelegate__ctor_m489758422_0 (CrossContextDelegate_t2085016836_0 * __this, Object_t * ___object, IntPtr_t ___method, const MethodInfo* method) IL2CPP_METHOD_ATTR;
// System.Void System.Runtime.Remoting.Contexts.CrossContextDelegate::Invoke()
extern "C" void CrossContextDelegate_Invoke_m_1104172368_0 (CrossContextDelegate_t2085016836_0 * __this, const MethodInfo* method) IL2CPP_METHOD_ATTR;
extern "C" void pinvoke_delegate_wrapper_CrossContextDelegate_t2085016836_0(Il2CppObject* delegate);
// System.IAsyncResult System.Runtime.Remoting.Contexts.CrossContextDelegate::BeginInvoke(System.AsyncCallback,System.Object)
extern "C" Object_t * CrossContextDelegate_BeginInvoke_m1978908379_0 (CrossContextDelegate_t2085016836_0 * __this, AsyncCallback_t_626615168_0 * ___callback, Object_t * ___object, const MethodInfo* method) IL2CPP_METHOD_ATTR;
// System.Void System.Runtime.Remoting.Contexts.CrossContextDelegate::EndInvoke(System.IAsyncResult)
extern "C" void CrossContextDelegate_EndInvoke_m_1822331930_0 (CrossContextDelegate_t2085016836_0 * __this, Object_t * ___result, const MethodInfo* method) IL2CPP_METHOD_ATTR;
| [
"[email protected]"
] | |
cdb23783f840ab078e7bf03f5825697e378d2e08 | a52f9f1165a97a161e371e5d2c72fdd61593341f | /external/cfitsio/testprog.c | b684b7ee1e0be4e631f6617fbf84cde47f5eb408 | [
"LGPL-3.0-only",
"LGPL-2.0-or-later",
"Zlib",
"MIT",
"CFITSIO"
] | permissive | AstrocatApp/AstrocatApp | 3c27d7b1c1413dbc531f8ed973da3d3d525f59ff | 0b3b33861260ed495bfcbd4c8601ab82ad247d37 | refs/heads/master | 2023-08-12T01:07:57.961008 | 2021-05-25T05:15:24 | 2021-05-25T05:15:24 | 335,548,027 | 2 | 1 | MIT | 2021-10-07T05:15:50 | 2021-02-03T07:53:32 | C++ | UTF-8 | C | false | false | 85,934 | c | #include <string.h>
#include <stdlib.h>
#include "fitsio.h"
int main(void);
int main()
{
/*
This is a big and complicated program that tests most of
the cfitsio routines. This code does not represent
the most efficient method of reading or writing FITS files
because this code is primarily designed to stress the cfitsio
library routines.
*/
char asciisum[17];
unsigned long checksum, datsum;
int datastatus, hdustatus, filemode;
int status, simple, bitpix, naxis, extend, hdutype, hdunum, tfields;
long ii, jj, extvers;
int nkeys, nfound, colnum, typecode, signval,nmsg;
char cval, cvalstr[2];
long repeat, offset, width, jnulval;
int anynull;
/* float vers; */
unsigned char xinarray[21], binarray[21], boutarray[21], bnul;
short iinarray[21], ioutarray[21], inul;
int kinarray[21], koutarray[21], knul;
long jinarray[21], joutarray[21], jnul;
float einarray[21], eoutarray[21], enul, cinarray[42];
double dinarray[21], doutarray[21], dnul, minarray[42];
double scale, zero;
long naxes[3], pcount, gcount, npixels, nrows, rowlen, firstpix[3];
int existkeys, morekeys, keynum;
char larray[42], larray2[42], colname[70], tdisp[40], nulstr[40];
char oskey[] = "value_string";
char iskey[21];
int olkey = 1;
int ilkey;
short oshtkey, ishtkey;
long ojkey = 11, ijkey;
long otint = 12345678;
float ofkey = 12.121212f;
float oekey = 13.131313f, iekey;
double ogkey = 14.1414141414141414;
double odkey = 15.1515151515151515, idkey;
double otfrac = .1234567890123456;
double xrval,yrval,xrpix,yrpix,xinc,yinc,rot,xpos,ypos,xpix,ypix;
char xcoordtype[] = "RA---TAN";
char ycoordtype[] = "DEC--TAN";
char ctype[5];
char *lsptr; /* pointer to long string value */
char comm[73];
char *comms[3];
char *inskey[21];
char *onskey[3] = {"first string", "second string", " "};
char *inclist[2] = {"key*", "newikys"};
char *exclist[2] = {"key_pr*", "key_pkls"};
int onlkey[3] = {1, 0, 1}, inlkey[3];
long onjkey[3] = {11, 12, 13}, injkey[3];
float onfkey[3] = {12.121212f, 13.131313f, 14.141414f};
float onekey[3] = {13.131313f, 14.141414f, 15.151515f}, inekey[3];
double ongkey[3] = {14.1414141414141414, 15.1515151515151515,
16.1616161616161616};
double ondkey[3] = {15.1515151515151515, 16.1616161616161616,
17.1717171717171717}, indkey[3];
long tbcol[5] = {1, 17, 28, 43, 56};
char filename[40], card[FLEN_CARD], card2[FLEN_CARD];
char keyword[FLEN_KEYWORD];
char value[FLEN_VALUE], comment[FLEN_COMMENT];
unsigned char uchars[80];
fitsfile *fptr, *tmpfptr;
char *ttype[10], *tform[10], *tunit[10];
char tblname[40];
char binname[] = "Test-BINTABLE";
char templt[] = "testprog.tpt";
char errmsg[FLEN_ERRMSG];
short imgarray[30][19], imgarray2[20][10];
long fpixels[2], lpixels[2], inc[2];
status = 0;
strcpy(tblname, "Test-ASCII");
/* ffvers(&vers);
printf("CFITSIO TESTPROG, v%.3f\n\n",vers);
*/
printf("CFITSIO TESTPROG\n\n");
printf("Try opening then closing a nonexistent file:\n");
fits_open_file(&fptr, "tq123x.kjl", READWRITE, &status);
printf(" ffopen fptr, status = %lu %d (expect an error)\n",
(unsigned long) fptr, status);
ffclos(fptr, &status);
printf(" ffclos status = %d\n\n", status);
ffcmsg();
status = 0;
for (ii = 0; ii < 21; ii++) /* allocate space for string column value */
inskey[ii] = (char *) malloc(21);
for (ii = 0; ii < 10; ii++)
{
ttype[ii] = (char *) malloc(20);
tform[ii] = (char *) malloc(20);
tunit[ii] = (char *) malloc(20);
}
comms[0] = comm;
/* delete previous version of the file, if it exists (with ! prefix) */
strcpy(filename, "!testprog.fit");
status = 0;
/*
#####################
# create FITS file #
#####################
*/
ffinit(&fptr, filename, &status);
printf("ffinit create new file status = %d\n", status);
if (status)
goto errstatus;
filename[0] = '\0';
ffflnm(fptr, filename, &status);
ffflmd(fptr, &filemode, &status);
printf("Name of file = %s, I/O mode = %d\n", filename, filemode);
simple = 1;
bitpix = 32;
naxis = 2;
naxes[0] = 10;
naxes[1] = 2;
npixels = 20;
pcount = 0;
gcount = 1;
extend = 1;
/*
############################
# write single keywords #
############################
*/
if (ffphps(fptr, bitpix, naxis, naxes, &status) > 0)
printf("ffphps status = %d\n", status);
if (ffprec(fptr,
"key_prec= 'This keyword was written by fxprec' / comment goes here",
&status) > 0 )
printf("ffprec status = %d\n", status);
printf("\ntest writing of long string keywords:\n");
strcpy(card, "1234567890123456789012345678901234567890");
strcat(card, "12345678901234567890123456789012345");
ffpkys(fptr, "card1", card, "", &status);
ffgkey(fptr, "card1", card2, comment, &status);
printf(" %s\n%s\n", card, card2);
strcpy(card, "1234567890123456789012345678901234567890");
strcat(card, "123456789012345678901234'6789012345");
ffpkys(fptr, "card2", card, "", &status);
ffgkey(fptr, "card2", card2, comment, &status);
printf(" %s\n%s\n", card, card2);
strcpy(card, "1234567890123456789012345678901234567890");
strcat(card, "123456789012345678901234''789012345");
ffpkys(fptr, "card3", card, "", &status);
ffgkey(fptr, "card3", card2, comment, &status);
printf(" %s\n%s\n", card, card2);
strcpy(card, "1234567890123456789012345678901234567890");
strcat(card, "123456789012345678901234567'9012345");
ffpkys(fptr, "card4", card, "", &status);
ffgkey(fptr, "card4", card2, comment, &status);
printf(" %s\n%s\n", card, card2);
if (ffpkys(fptr, "key_pkys", oskey, "fxpkys comment", &status) > 0)
printf("ffpkys status = %d\n", status);
if (ffpkyl(fptr, "key_pkyl", olkey, "fxpkyl comment", &status) > 0)
printf("ffpkyl status = %d\n", status);
if (ffpkyj(fptr, "key_pkyj", ojkey, "fxpkyj comment", &status) > 0)
printf("ffpkyj status = %d\n", status);
if (ffpkyf(fptr, "key_pkyf", ofkey, 5, "fxpkyf comment", &status) > 0)
printf("ffpkyf status = %d\n", status);
if (ffpkye(fptr, "key_pkye", oekey, 6, "fxpkye comment", &status) > 0)
printf("ffpkye status = %d\n", status);
if (ffpkyg(fptr, "key_pkyg", ogkey, 14, "fxpkyg comment", &status) > 0)
printf("ffpkyg status = %d\n", status);
if (ffpkyd(fptr, "key_pkyd", odkey, 14, "fxpkyd comment", &status) > 0)
printf("ffpkyd status = %d\n", status);
if (ffpkyc(fptr, "key_pkyc", onekey, 6, "fxpkyc comment", &status) > 0)
printf("ffpkyc status = %d\n", status);
if (ffpkym(fptr, "key_pkym", ondkey, 14, "fxpkym comment", &status) > 0)
printf("ffpkym status = %d\n", status);
if (ffpkfc(fptr, "key_pkfc", onekey, 6, "fxpkfc comment", &status) > 0)
printf("ffpkfc status = %d\n", status);
if (ffpkfm(fptr, "key_pkfm", ondkey, 14, "fxpkfm comment", &status) > 0)
printf("ffpkfm status = %d\n", status);
if (ffpkls(fptr, "key_pkls",
"This is a very long string value that is continued over more than one keyword.",
"fxpkls comment", &status) > 0)
printf("ffpkls status = %d\n", status);
if (ffplsw(fptr, &status) > 0 )
printf("ffplsw status = %d\n", status);
if (ffpkyt(fptr, "key_pkyt", otint, otfrac, "fxpkyt comment", &status) > 0)
printf("ffpkyt status = %d\n", status);
if (ffpcom(fptr, " This keyword was written by fxpcom.", &status) > 0)
printf("ffpcom status = %d\n", status);
if (ffphis(fptr, " This keyword written by fxphis (w/ 2 leading spaces).",
&status) > 0)
printf("ffphis status = %d\n", status);
if (ffpdat(fptr, &status) > 0)
{
printf("ffpdat status = %d\n", status);
goto errstatus;
}
/*
###############################
# write arrays of keywords #
###############################
*/
nkeys = 3;
comms[0] = comm; /* use the inskey array of pointers for the comments */
strcpy(comm, "fxpkns comment&");
if (ffpkns(fptr, "ky_pkns", 1, nkeys, onskey, comms, &status) > 0)
printf("ffpkns status = %d\n", status);
strcpy(comm, "fxpknl comment&");
if (ffpknl(fptr, "ky_pknl", 1, nkeys, onlkey, comms, &status) > 0)
printf("ffpknl status = %d\n", status);
strcpy(comm, "fxpknj comment&");
if (ffpknj(fptr, "ky_pknj", 1, nkeys, onjkey, comms, &status) > 0)
printf("ffpknj status = %d\n", status);
strcpy(comm, "fxpknf comment&");
if (ffpknf(fptr, "ky_pknf", 1, nkeys, onfkey, 5, comms, &status) > 0)
printf("ffpknf status = %d\n", status);
strcpy(comm, "fxpkne comment&");
if (ffpkne(fptr, "ky_pkne", 1, nkeys, onekey, 6, comms, &status) > 0)
printf("ffpkne status = %d\n", status);
strcpy(comm, "fxpkng comment&");
if (ffpkng(fptr, "ky_pkng", 1, nkeys, ongkey, 13, comms, &status) > 0)
printf("ffpkng status = %d\n", status);
strcpy(comm, "fxpknd comment&");
if (ffpknd(fptr, "ky_pknd", 1, nkeys, ondkey, 14, comms, &status) > 0)
{
printf("ffpknd status = %d\n", status);
goto errstatus;
}
/*
############################
# write generic keywords #
############################
*/
strcpy(oskey, "1");
if (ffpky(fptr, TSTRING, "tstring", oskey, "tstring comment", &status) > 0)
printf("ffpky status = %d\n", status);
olkey = TLOGICAL;
if (ffpky(fptr, TLOGICAL, "tlogical", &olkey, "tlogical comment",
&status) > 0)
printf("ffpky status = %d\n", status);
cval = TBYTE;
if (ffpky(fptr, TBYTE, "tbyte", &cval, "tbyte comment", &status) > 0)
printf("ffpky status = %d\n", status);
oshtkey = TSHORT;
if (ffpky(fptr, TSHORT, "tshort", &oshtkey, "tshort comment", &status) > 0)
printf("ffpky status = %d\n", status);
olkey = TINT;
if (ffpky(fptr, TINT, "tint", &olkey, "tint comment", &status) > 0)
printf("ffpky status = %d\n", status);
ojkey = TLONG;
if (ffpky(fptr, TLONG, "tlong", &ojkey, "tlong comment", &status) > 0)
printf("ffpky status = %d\n", status);
oekey = TFLOAT;
if (ffpky(fptr, TFLOAT, "tfloat", &oekey, "tfloat comment", &status) > 0)
printf("ffpky status = %d\n", status);
odkey = TDOUBLE;
if (ffpky(fptr, TDOUBLE, "tdouble", &odkey, "tdouble comment",
&status) > 0)
printf("ffpky status = %d\n", status);
/*
############################
# write data #
############################
*/
/* define the null value (must do this before writing any data) */
if (ffpkyj(fptr, "BLANK", -99, "value to use for undefined pixels",
&status) > 0)
printf("BLANK keyword status = %d\n", status);
/* initialize arrays of values to write to primary array */
for (ii = 0; ii < npixels; ii++)
{
boutarray[ii] = (unsigned char) (ii + 1);
ioutarray[ii] = (short) (ii + 1);
joutarray[ii] = ii + 1;
eoutarray[ii] = (float) (ii + 1);
doutarray[ii] = ii + 1;
}
/* write a few pixels with each datatype */
/* set the last value in each group of 4 as undefined */
/*
ffpprb(fptr, 1, 1, 2, &boutarray[0], &status);
ffppri(fptr, 1, 5, 2, &ioutarray[4], &status);
ffpprj(fptr, 1, 9, 2, &joutarray[8], &status);
ffppre(fptr, 1, 13, 2, &eoutarray[12], &status);
ffpprd(fptr, 1, 17, 2, &doutarray[16], &status);
*/
/* test the newer ffpx routine, instead of the older ffppr_ routines */
firstpix[0]=1;
firstpix[1]=1;
ffppx(fptr, TBYTE, firstpix, 2, &boutarray[0], &status);
firstpix[0]=5;
ffppx(fptr, TSHORT, firstpix, 2, &ioutarray[4], &status);
firstpix[0]=9;
ffppx(fptr, TLONG, firstpix, 2, &joutarray[8], &status);
firstpix[0]=3;
firstpix[1]=2;
ffppx(fptr, TFLOAT, firstpix, 2, &eoutarray[12], &status);
firstpix[0]=7;
ffppx(fptr, TDOUBLE, firstpix, 2, &doutarray[16], &status);
/*
ffppnb(fptr, 1, 3, 2, &boutarray[2], 4, &status);
ffppni(fptr, 1, 7, 2, &ioutarray[6], 8, &status);
ffppnj(fptr, 1, 11, 2, &joutarray[10], 12, &status);
ffppne(fptr, 1, 15, 2, &eoutarray[14], 16., &status);
ffppnd(fptr, 1, 19, 2, &doutarray[18], 20., &status);
*/
firstpix[0]=3;
firstpix[1]=1;
bnul = 4;
ffppxn(fptr, TBYTE, firstpix, 2, &boutarray[2], &bnul, &status);
firstpix[0]=7;
inul = 8;
ffppxn(fptr, TSHORT, firstpix, 2, &ioutarray[6], &inul, &status);
firstpix[0]=1;
firstpix[1]=2;
jnul = 12;
ffppxn(fptr, TLONG, firstpix, 2, &joutarray[10], &jnul, &status);
firstpix[0]=5;
enul = 16.;
ffppxn(fptr, TFLOAT, firstpix, 2, &eoutarray[14], &enul, &status);
firstpix[0]=9;
dnul = 20.;
ffppxn(fptr, TDOUBLE, firstpix, 2, &doutarray[18], &dnul, &status);
ffppru(fptr, 1, 1, 1, &status);
if (status > 0)
{
printf("ffppnx status = %d\n", status);
goto errstatus;
}
ffflus(fptr, &status); /* flush all data to the disk file */
printf("ffflus status = %d\n", status);
printf("HDU number = %d\n", ffghdn(fptr, &hdunum));
/*
############################
# read data #
############################
*/
/* read back the data, setting null values = 99 */
printf("\nValues read back from primary array (99 = null pixel)\n");
printf("The 1st, and every 4th pixel should be undefined:\n");
anynull = 0;
ffgpvb(fptr, 1, 1, 10, 99, binarray, &anynull, &status);
ffgpvb(fptr, 1, 11, 10, 99, &binarray[10], &anynull, &status);
for (ii = 0; ii < npixels; ii++)
printf(" %2d", binarray[ii]);
printf(" %d (ffgpvb)\n", anynull);
ffgpvi(fptr, 1, 1, npixels, 99, iinarray, &anynull, &status);
for (ii = 0; ii < npixels; ii++)
printf(" %2d", iinarray[ii]);
printf(" %d (ffgpvi)\n", anynull);
ffgpvj(fptr, 1, 1, npixels, 99, jinarray, &anynull, &status);
for (ii = 0; ii < npixels; ii++)
printf(" %2ld", jinarray[ii]);
printf(" %d (ffgpvj)\n", anynull);
ffgpve(fptr, 1, 1, npixels, 99., einarray, &anynull, &status);
for (ii = 0; ii < npixels; ii++)
printf(" %2.0f", einarray[ii]);
printf(" %d (ffgpve)\n", anynull);
ffgpvd(fptr, 1, 1, 10, 99., dinarray, &anynull, &status);
ffgpvd(fptr, 1, 11, 10, 99., &dinarray[10], &anynull, &status);
for (ii = 0; ii < npixels; ii++)
printf(" %2.0f", dinarray[ii]);
printf(" %d (ffgpvd)\n", anynull);
if (status > 0)
{
printf("ERROR: ffgpv_ status = %d\n", status);
goto errstatus;
}
if (anynull == 0)
printf("ERROR: ffgpv_ did not detect null values\n");
/* reset the output null value to the expected input value */
for (ii = 3; ii < npixels; ii += 4)
{
boutarray[ii] = 99;
ioutarray[ii] = 99;
joutarray[ii] = 99;
eoutarray[ii] = 99.;
doutarray[ii] = 99.;
}
ii = 0;
boutarray[ii] = 99;
ioutarray[ii] = 99;
joutarray[ii] = 99;
eoutarray[ii] = 99.;
doutarray[ii] = 99.;
/* compare the output with the input; flag any differences */
for (ii = 0; ii < npixels; ii++)
{
if (boutarray[ii] != binarray[ii])
printf("bout != bin = %u %u \n", boutarray[ii], binarray[ii]);
if (ioutarray[ii] != iinarray[ii])
printf("iout != iin = %d %d \n", ioutarray[ii], iinarray[ii]);
if (joutarray[ii] != jinarray[ii])
printf("jout != jin = %ld %ld \n", joutarray[ii], jinarray[ii]);
if (eoutarray[ii] != einarray[ii])
printf("eout != ein = %f %f \n", eoutarray[ii], einarray[ii]);
if (doutarray[ii] != dinarray[ii])
printf("dout != din = %f %f \n", doutarray[ii], dinarray[ii]);
}
for (ii = 0; ii < npixels; ii++)
{
binarray[ii] = 0;
iinarray[ii] = 0;
jinarray[ii] = 0;
einarray[ii] = 0.;
dinarray[ii] = 0.;
}
anynull = 0;
ffgpfb(fptr, 1, 1, 10, binarray, larray, &anynull, &status);
ffgpfb(fptr, 1, 11, 10, &binarray[10], &larray[10], &anynull, &status);
for (ii = 0; ii < npixels; ii++)
if (larray[ii])
printf(" *");
else
printf(" %2d", binarray[ii]);
printf(" %d (ffgpfb)\n", anynull);
ffgpfi(fptr, 1, 1, npixels, iinarray, larray, &anynull, &status);
for (ii = 0; ii < npixels; ii++)
if (larray[ii])
printf(" *");
else
printf(" %2d", iinarray[ii]);
printf(" %d (ffgpfi)\n", anynull);
ffgpfj(fptr, 1, 1, npixels, jinarray, larray, &anynull, &status);
for (ii = 0; ii < npixels; ii++)
if (larray[ii])
printf(" *");
else
printf(" %2ld", jinarray[ii]);
printf(" %d (ffgpfj)\n", anynull);
ffgpfe(fptr, 1, 1, npixels, einarray, larray, &anynull, &status);
for (ii = 0; ii < npixels; ii++)
if (larray[ii])
printf(" *");
else
printf(" %2.0f", einarray[ii]);
printf(" %d (ffgpfe)\n", anynull);
ffgpfd(fptr, 1, 1, 10, dinarray, larray, &anynull, &status);
ffgpfd(fptr, 1, 11, 10, &dinarray[10], &larray[10], &anynull, &status);
for (ii = 0; ii < npixels; ii++)
if (larray[ii])
printf(" *");
else
printf(" %2.0f", dinarray[ii]);
printf(" %d (ffgpfd)\n", anynull);
if (status > 0)
{
printf("ERROR: ffgpf_ status = %d\n", status);
goto errstatus;
}
if (anynull == 0)
printf("ERROR: ffgpf_ did not detect null values\n");
/*
##########################################
# close and reopen file multiple times #
##########################################
*/
for (ii = 0; ii < 10; ii++)
{
if (ffclos(fptr, &status) > 0)
{
printf("ERROR in ftclos (1) = %d", status);
goto errstatus;
}
if (fits_open_file(&fptr, filename, READWRITE, &status) > 0)
{
printf("ERROR: ffopen open file status = %d\n", status);
goto errstatus;
}
}
printf("\nClosed then reopened the FITS file 10 times.\n");
printf("HDU number = %d\n", ffghdn(fptr, &hdunum));
filename[0] = '\0';
ffflnm(fptr, filename, &status);
ffflmd(fptr, &filemode, &status);
printf("Name of file = %s, I/O mode = %d\n", filename, filemode);
/*
############################
# read single keywords #
############################
*/
simple = 0;
bitpix = 0;
naxis = 0;
naxes[0] = 0;
naxes[1] = 0;
pcount = -99;
gcount = -99;
extend = -99;
printf("\nRead back keywords:\n");
ffghpr(fptr, 99, &simple, &bitpix, &naxis, naxes, &pcount,
&gcount, &extend, &status);
printf("simple = %d, bitpix = %d, naxis = %d, naxes = (%ld, %ld)\n",
simple, bitpix, naxis, naxes[0], naxes[1]);
printf(" pcount = %ld, gcount = %ld, extend = %d\n",
pcount, gcount, extend);
ffgrec(fptr, 9, card, &status);
printf("%s\n", card);
if (strncmp(card, "KEY_PREC= 'This", 15) )
printf("ERROR in ffgrec\n");
ffgkyn(fptr, 9, keyword, value, comment, &status);
printf("%s : %s : %s :\n",keyword, value, comment);
if (strncmp(keyword, "KEY_PREC", 8) )
printf("ERROR in ffgkyn: %s\n", keyword);
ffgcrd(fptr, keyword, card, &status);
printf("%s\n", card);
if (strncmp(keyword, card, 8) )
printf("ERROR in ffgcrd: %s\n", keyword);
ffgkey(fptr, "KY_PKNS1", value, comment, &status);
printf("KY_PKNS1 : %s : %s :\n", value, comment);
if (strncmp(value, "'first string'", 14) )
printf("ERROR in ffgkey: %s\n", value);
ffgkys(fptr, "key_pkys", iskey, comment, &status);
printf("KEY_PKYS %s %s %d\n", iskey, comment, status);
ffgkyl(fptr, "key_pkyl", &ilkey, comment, &status);
printf("KEY_PKYL %d %s %d\n", ilkey, comment, status);
ffgkyj(fptr, "KEY_PKYJ", &ijkey, comment, &status);
printf("KEY_PKYJ %ld %s %d\n",ijkey, comment, status);
ffgkye(fptr, "KEY_PKYJ", &iekey, comment, &status);
printf("KEY_PKYJ %f %s %d\n",iekey, comment, status);
ffgkyd(fptr, "KEY_PKYJ", &idkey, comment, &status);
printf("KEY_PKYJ %f %s %d\n",idkey, comment, status);
if (ijkey != 11 || iekey != 11. || idkey != 11.)
printf("ERROR in ffgky[jed]: %ld, %f, %f\n",ijkey, iekey, idkey);
iskey[0] = '\0';
ffgky(fptr, TSTRING, "key_pkys", iskey, comment, &status);
printf("KEY_PKY S %s %s %d\n", iskey, comment, status);
ilkey = 0;
ffgky(fptr, TLOGICAL, "key_pkyl", &ilkey, comment, &status);
printf("KEY_PKY L %d %s %d\n", ilkey, comment, status);
ffgky(fptr, TBYTE, "KEY_PKYJ", &cval, comment, &status);
printf("KEY_PKY BYTE %d %s %d\n",cval, comment, status);
ffgky(fptr, TSHORT, "KEY_PKYJ", &ishtkey, comment, &status);
printf("KEY_PKY SHORT %d %s %d\n",ishtkey, comment, status);
ffgky(fptr, TINT, "KEY_PKYJ", &ilkey, comment, &status);
printf("KEY_PKY INT %d %s %d\n",ilkey, comment, status);
ijkey = 0;
ffgky(fptr, TLONG, "KEY_PKYJ", &ijkey, comment, &status);
printf("KEY_PKY J %ld %s %d\n",ijkey, comment, status);
iekey = 0;
ffgky(fptr, TFLOAT, "KEY_PKYE", &iekey, comment, &status);
printf("KEY_PKY E %f %s %d\n",iekey, comment, status);
idkey = 0;
ffgky(fptr, TDOUBLE, "KEY_PKYD", &idkey, comment, &status);
printf("KEY_PKY D %f %s %d\n",idkey, comment, status);
ffgkyd(fptr, "KEY_PKYF", &idkey, comment, &status);
printf("KEY_PKYF %f %s %d\n",idkey, comment, status);
ffgkyd(fptr, "KEY_PKYE", &idkey, comment, &status);
printf("KEY_PKYE %f %s %d\n",idkey, comment, status);
ffgkyd(fptr, "KEY_PKYG", &idkey, comment, &status);
printf("KEY_PKYG %.14f %s %d\n",idkey, comment, status);
ffgkyd(fptr, "KEY_PKYD", &idkey, comment, &status);
printf("KEY_PKYD %.14f %s %d\n",idkey, comment, status);
ffgkyc(fptr, "KEY_PKYC", inekey, comment, &status);
printf("KEY_PKYC %f %f %s %d\n",inekey[0], inekey[1], comment, status);
ffgkyc(fptr, "KEY_PKFC", inekey, comment, &status);
printf("KEY_PKFC %f %f %s %d\n",inekey[0], inekey[1], comment, status);
ffgkym(fptr, "KEY_PKYM", indkey, comment, &status);
printf("KEY_PKYM %f %f %s %d\n",indkey[0], indkey[1], comment, status);
ffgkym(fptr, "KEY_PKFM", indkey, comment, &status);
printf("KEY_PKFM %f %f %s %d\n",indkey[0], indkey[1], comment, status);
ffgkyt(fptr, "KEY_PKYT", &ijkey, &idkey, comment, &status);
printf("KEY_PKYT %ld %.14f %s %d\n",ijkey, idkey, comment, status);
ffpunt(fptr, "KEY_PKYJ", "km/s/Mpc", &status);
ijkey = 0;
ffgky(fptr, TLONG, "KEY_PKYJ", &ijkey, comment, &status);
printf("KEY_PKY J %ld %s %d\n",ijkey, comment, status);
ffgunt(fptr,"KEY_PKYJ", comment, &status);
printf("KEY_PKY units = %s\n",comment);
ffpunt(fptr, "KEY_PKYJ", "", &status);
ijkey = 0;
ffgky(fptr, TLONG, "KEY_PKYJ", &ijkey, comment, &status);
printf("KEY_PKY J %ld %s %d\n",ijkey, comment, status);
ffgunt(fptr,"KEY_PKYJ", comment, &status);
printf("KEY_PKY units = %s\n",comment);
ffpunt(fptr, "KEY_PKYJ", "feet/second/second", &status);
ijkey = 0;
ffgky(fptr, TLONG, "KEY_PKYJ", &ijkey, comment, &status);
printf("KEY_PKY J %ld %s %d\n",ijkey, comment, status);
ffgunt(fptr,"KEY_PKYJ", comment, &status);
printf("KEY_PKY units = %s\n",comment);
ffgkls(fptr, "key_pkls", &lsptr, comment, &status);
printf("KEY_PKLS long string value = \n%s\n", lsptr);
/* free the memory for the long string value */
fits_free_memory(lsptr, &status);
/* get size and position in header */
ffghps(fptr, &existkeys, &keynum, &status);
printf("header contains %d keywords; located at keyword %d \n",existkeys,
keynum);
/*
############################
# read array keywords #
############################
*/
ffgkns(fptr, "ky_pkns", 1, 3, inskey, &nfound, &status);
printf("ffgkns: %s, %s, %s\n", inskey[0], inskey[1], inskey[2]);
if (nfound != 3 || status > 0)
printf("\nERROR in ffgkns %d, %d\n", nfound, status);
ffgknl(fptr, "ky_pknl", 1, 3, inlkey, &nfound, &status);
printf("ffgknl: %d, %d, %d\n", inlkey[0], inlkey[1], inlkey[2]);
if (nfound != 3 || status > 0)
printf("\nERROR in ffgknl %d, %d\n", nfound, status);
ffgknj(fptr, "ky_pknj", 1, 3, injkey, &nfound, &status);
printf("ffgknj: %ld, %ld, %ld\n", injkey[0], injkey[1], injkey[2]);
if (nfound != 3 || status > 0)
printf("\nERROR in ffgknj %d, %d\n", nfound, status);
ffgkne(fptr, "ky_pkne", 1, 3, inekey, &nfound, &status);
printf("ffgkne: %f, %f, %f\n", inekey[0], inekey[1], inekey[2]);
if (nfound != 3 || status > 0)
printf("\nERROR in ffgkne %d, %d\n", nfound, status);
ffgknd(fptr, "ky_pknd", 1, 3, indkey, &nfound, &status);
printf("ffgknd: %f, %f, %f\n", indkey[0], indkey[1], indkey[2]);
if (nfound != 3 || status > 0)
printf("\nERROR in ffgknd %d, %d\n", nfound, status);
/* get position of HISTORY keyword for subsequent deletes and inserts */
ffgcrd(fptr, "HISTORY", card, &status);
ffghps(fptr, &existkeys, &keynum, &status);
keynum -= 2;
printf("\nBefore deleting the HISTORY and DATE keywords...\n");
for (ii = keynum; ii <= keynum + 3; ii++)
{
ffgrec(fptr, ii, card, &status);
printf("%.8s\n", card); /* don't print date value, so that */
} /* the output will always be the same */
/*
############################
# delete keywords #
############################
*/
ffdrec(fptr, keynum + 1, &status);
ffdkey(fptr, "DATE", &status);
printf("\nAfter deleting the keywords...\n");
for (ii = keynum; ii <= keynum + 1; ii++)
{
ffgrec(fptr, ii, card, &status);
printf("%s\n", card);
}
if (status > 0)
printf("\nERROR deleting keywords\n");
/*
############################
# insert keywords #
############################
*/
keynum += 4;
ffirec(fptr, keynum - 3, "KY_IREC = 'This keyword inserted by fxirec'",
&status);
ffikys(fptr, "KY_IKYS", "insert_value_string", "ikys comment", &status);
ffikyj(fptr, "KY_IKYJ", 49, "ikyj comment", &status);
ffikyl(fptr, "KY_IKYL", 1, "ikyl comment", &status);
ffikye(fptr, "KY_IKYE", 12.3456f, 4, "ikye comment", &status);
ffikyd(fptr, "KY_IKYD", 12.345678901234567, 14, "ikyd comment", &status);
ffikyf(fptr, "KY_IKYF", 12.3456f, 4, "ikyf comment", &status);
ffikyg(fptr, "KY_IKYG", 12.345678901234567, 13, "ikyg comment", &status);
printf("\nAfter inserting the keywords...\n");
for (ii = keynum - 4; ii <= keynum + 5; ii++)
{
ffgrec(fptr, ii, card, &status);
printf("%s\n", card);
}
if (status > 0)
printf("\nERROR inserting keywords\n");
/*
############################
# modify keywords #
############################
*/
ffmrec(fptr, keynum - 4, "COMMENT This keyword was modified by fxmrec", &status);
ffmcrd(fptr, "KY_IREC", "KY_MREC = 'This keyword was modified by fxmcrd'",
&status);
ffmnam(fptr, "KY_IKYS", "NEWIKYS", &status);
ffmcom(fptr, "KY_IKYJ","This is a modified comment", &status);
ffmkyj(fptr, "KY_IKYJ", 50, "&", &status);
ffmkyl(fptr, "KY_IKYL", 0, "&", &status);
ffmkys(fptr, "NEWIKYS", "modified_string", "&", &status);
ffmkye(fptr, "KY_IKYE", -12.3456f, 4, "&", &status);
ffmkyd(fptr, "KY_IKYD", -12.345678901234567, 14, "modified comment",
&status);
ffmkyf(fptr, "KY_IKYF", -12.3456f, 4, "&", &status);
ffmkyg(fptr, "KY_IKYG", -12.345678901234567, 13, "&", &status);
printf("\nAfter modifying the keywords...\n");
for (ii = keynum - 4; ii <= keynum + 5; ii++)
{
ffgrec(fptr, ii, card, &status);
printf("%s\n", card);
}
if (status > 0)
printf("\nERROR modifying keywords\n");
/*
############################
# update keywords #
############################
*/
ffucrd(fptr, "KY_MREC", "KY_UCRD = 'This keyword was updated by fxucrd'",
&status);
ffukyj(fptr, "KY_IKYJ", 51, "&", &status);
ffukyl(fptr, "KY_IKYL", 1, "&", &status);
ffukys(fptr, "NEWIKYS", "updated_string", "&", &status);
ffukye(fptr, "KY_IKYE", -13.3456f, 4, "&", &status);
ffukyd(fptr, "KY_IKYD", -13.345678901234567, 14, "modified comment",
&status);
ffukyf(fptr, "KY_IKYF", -13.3456f, 4, "&", &status);
ffukyg(fptr, "KY_IKYG", -13.345678901234567, 13, "&", &status);
printf("\nAfter updating the keywords...\n");
for (ii = keynum - 4; ii <= keynum + 5; ii++)
{
ffgrec(fptr, ii, card, &status);
printf("%s\n", card);
}
if (status > 0)
printf("\nERROR modifying keywords\n");
/* move to top of header and find keywords using wild cards */
ffgrec(fptr, 0, card, &status);
printf("\nKeywords found using wildcard search (should be 13)...\n");
nfound = 0;
while (!ffgnxk(fptr,inclist, 2, exclist, 2, card, &status))
{
nfound++;
printf("%s\n", card);
}
if (nfound != 13)
{
printf("\nERROR reading keywords using wildcards (ffgnxk)\n");
goto errstatus;
}
status = 0;
/*
############################
# copy index keyword #
############################
*/
ffcpky(fptr, fptr, 1, 4, "KY_PKNE", &status);
ffgkne(fptr, "ky_pkne", 2, 4, inekey, &nfound, &status);
printf("\nCopied keyword: ffgkne: %f, %f, %f\n", inekey[0], inekey[1],
inekey[2]);
if (status > 0)
{
printf("\nERROR in ffgkne %d, %d\n", nfound, status);
goto errstatus;
}
/*
######################################
# modify header using template file #
######################################
*/
if (ffpktp(fptr, templt, &status))
{
printf("\nERROR returned by ffpktp:\n");
printf("Could not open or process the file 'testprog.tpt'.\n");
printf(" This file is included with the CFITSIO distribution\n");
printf(" and should be copied into the current directory\n");
printf(" before running the testprog program.\n");
status = 0;
}
printf("Updated header using template file (ffpktp)\n");
/*
############################
# create binary table #
############################
*/
strcpy(tform[0], "15A");
strcpy(tform[1], "1L");
strcpy(tform[2], "16X");
strcpy(tform[3], "1B");
strcpy(tform[4], "1I");
strcpy(tform[5], "1J");
strcpy(tform[6], "1E");
strcpy(tform[7], "1D");
strcpy(tform[8], "1C");
strcpy(tform[9], "1M");
strcpy(ttype[0], "Avalue");
strcpy(ttype[1], "Lvalue");
strcpy(ttype[2], "Xvalue");
strcpy(ttype[3], "Bvalue");
strcpy(ttype[4], "Ivalue");
strcpy(ttype[5], "Jvalue");
strcpy(ttype[6], "Evalue");
strcpy(ttype[7], "Dvalue");
strcpy(ttype[8], "Cvalue");
strcpy(ttype[9], "Mvalue");
strcpy(tunit[0], "");
strcpy(tunit[1], "m**2");
strcpy(tunit[2], "cm");
strcpy(tunit[3], "erg/s");
strcpy(tunit[4], "km/s");
strcpy(tunit[5], "");
strcpy(tunit[6], "");
strcpy(tunit[7], "");
strcpy(tunit[8], "");
strcpy(tunit[9], "");
nrows = 21;
tfields = 10;
pcount = 0;
/*
ffcrtb(fptr, BINARY_TBL, nrows, tfields, ttype, tform, tunit, binname,
&status);
*/
ffibin(fptr, nrows, tfields, ttype, tform, tunit, binname, 0L,
&status);
printf("\nffibin status = %d\n", status);
printf("HDU number = %d\n", ffghdn(fptr, &hdunum));
/* get size and position in header, and reserve space for more keywords */
ffghps(fptr, &existkeys, &keynum, &status);
printf("header contains %d keywords; located at keyword %d \n",existkeys,
keynum);
morekeys = 40;
ffhdef(fptr, morekeys, &status);
ffghsp(fptr, &existkeys, &morekeys, &status);
printf("header contains %d keywords with room for %d more\n",existkeys,
morekeys);
fftnul(fptr, 4, 99, &status); /* define null value for int cols */
fftnul(fptr, 5, 99, &status);
fftnul(fptr, 6, 99, &status);
extvers = 1;
ffpkyj(fptr, "EXTVER", extvers, "extension version number", &status);
ffpkyj(fptr, "TNULL4", 99, "value for undefined pixels", &status);
ffpkyj(fptr, "TNULL5", 99, "value for undefined pixels", &status);
ffpkyj(fptr, "TNULL6", 99, "value for undefined pixels", &status);
naxis = 3;
naxes[0] = 1;
naxes[1] = 2;
naxes[2] = 8;
ffptdm(fptr, 3, naxis, naxes, &status);
naxis = 0;
naxes[0] = 0;
naxes[1] = 0;
naxes[2] = 0;
ffgtdm(fptr, 3, 3, &naxis, naxes, &status);
ffgkys(fptr, "TDIM3", iskey, comment, &status);
printf("TDIM3 = %s, %d, %ld, %ld, %ld\n", iskey, naxis, naxes[0],
naxes[1], naxes[2]);
ffrdef(fptr, &status); /* force header to be scanned (not required) */
/*
############################
# write data to columns #
############################
*/
/* initialize arrays of values to write to table */
signval = -1;
for (ii = 0; ii < 21; ii++)
{
signval *= -1;
boutarray[ii] = (unsigned char) (ii + 1);
ioutarray[ii] = (short) ((ii + 1) * signval);
joutarray[ii] = (ii + 1) * signval;
koutarray[ii] = (ii + 1) * signval;
eoutarray[ii] = (float) ((ii + 1) * signval);
doutarray[ii] = (ii + 1) * signval;
}
ffpcls(fptr, 1, 1, 1, 3, onskey, &status); /* write string values */
ffpclu(fptr, 1, 4, 1, 1, &status); /* write null value */
larray[0] = 0;
larray[1] = 1;
larray[2] = 0;
larray[3] = 0;
larray[4] = 1;
larray[5] = 1;
larray[6] = 0;
larray[7] = 0;
larray[8] = 0;
larray[9] = 1;
larray[10] = 1;
larray[11] = 1;
larray[12] = 0;
larray[13] = 0;
larray[14] = 0;
larray[15] = 0;
larray[16] = 1;
larray[17] = 1;
larray[18] = 1;
larray[19] = 1;
larray[20] = 0;
larray[21] = 0;
larray[22] = 0;
larray[23] = 0;
larray[24] = 0;
larray[25] = 1;
larray[26] = 1;
larray[27] = 1;
larray[28] = 1;
larray[29] = 1;
larray[30] = 0;
larray[31] = 0;
larray[32] = 0;
larray[33] = 0;
larray[34] = 0;
larray[35] = 0;
ffpclx(fptr, 3, 1, 1, 36, larray, &status); /*write bits*/
for (ii = 4; ii < 9; ii++) /* loop over cols 4 - 8 */
{
ffpclb(fptr, ii, 1, 1, 2, boutarray, &status);
if (status == NUM_OVERFLOW)
status = 0;
ffpcli(fptr, ii, 3, 1, 2, &ioutarray[2], &status);
if (status == NUM_OVERFLOW)
status = 0;
ffpclk(fptr, ii, 5, 1, 2, &koutarray[4], &status);
if (status == NUM_OVERFLOW)
status = 0;
ffpcle(fptr, ii, 7, 1, 2, &eoutarray[6], &status);
if (status == NUM_OVERFLOW)
status = 0;
ffpcld(fptr, ii, 9, 1, 2, &doutarray[8], &status);
if (status == NUM_OVERFLOW)
status = 0;
ffpclu(fptr, ii, 11, 1, 1, &status); /* write null value */
}
ffpclc(fptr, 9, 1, 1, 10, eoutarray, &status);
ffpclm(fptr, 10, 1, 1, 10, doutarray, &status);
for (ii = 4; ii < 9; ii++) /* loop over cols 4 - 8 */
{
ffpcnb(fptr, ii, 12, 1, 2, &boutarray[11], 13, &status);
if (status == NUM_OVERFLOW)
status = 0;
ffpcni(fptr, ii, 14, 1, 2, &ioutarray[13], 15, &status);
if (status == NUM_OVERFLOW)
status = 0;
ffpcnk(fptr, ii, 16, 1, 2, &koutarray[15], 17, &status);
if (status == NUM_OVERFLOW)
status = 0;
ffpcne(fptr, ii, 18, 1, 2, &eoutarray[17], 19., &status);
if (status == NUM_OVERFLOW)
status = 0;
ffpcnd(fptr, ii, 20, 1, 2, &doutarray[19], 21., &status);
if (status == NUM_OVERFLOW)
status = 0;
}
ffpcll(fptr, 2, 1, 1, 21, larray, &status); /*write logicals*/
ffpclu(fptr, 2, 11, 1, 1, &status); /* write null value */
printf("ffpcl_ status = %d\n", status);
/*
#########################################
# get information about the columns #
#########################################
*/
printf("\nFind the column numbers; a returned status value of 237 is");
printf("\nexpected and indicates that more than one column name matches");
printf("\nthe input column name template. Status = 219 indicates that");
printf("\nthere was no matching column name.");
ffgcno(fptr, 0, "Xvalue", &colnum, &status);
printf("\nColumn Xvalue is number %d; status = %d.\n", colnum, status);
while (status != COL_NOT_FOUND)
{
ffgcnn(fptr, 1, "*ue", colname, &colnum, &status);
printf("Column %s is number %d; status = %d.\n",
colname, colnum, status);
}
status = 0;
printf("\nInformation about each column:\n");
for (ii = 0; ii < tfields; ii++)
{
ffgtcl(fptr, ii + 1, &typecode, &repeat, &width, &status);
printf("%4s %3d %2ld %2ld", tform[ii], typecode, repeat, width);
ffgbcl(fptr, ii + 1, ttype[0], tunit[0], cvalstr, &repeat, &scale,
&zero, &jnulval, tdisp, &status);
printf(" %s, %s, %c, %ld, %f, %f, %ld, %s.\n",
ttype[0], tunit[0], cvalstr[0], repeat, scale, zero, jnulval, tdisp);
}
printf("\n");
/*
###############################################
# insert ASCII table before the binary table #
###############################################
*/
if (ffmrhd(fptr, -1, &hdutype, &status) > 0)
goto errstatus;
strcpy(tform[0], "A15");
strcpy(tform[1], "I10");
strcpy(tform[2], "F14.6");
strcpy(tform[3], "E12.5");
strcpy(tform[4], "D21.14");
strcpy(ttype[0], "Name");
strcpy(ttype[1], "Ivalue");
strcpy(ttype[2], "Fvalue");
strcpy(ttype[3], "Evalue");
strcpy(ttype[4], "Dvalue");
strcpy(tunit[0], "");
strcpy(tunit[1], "m**2");
strcpy(tunit[2], "cm");
strcpy(tunit[3], "erg/s");
strcpy(tunit[4], "km/s");
rowlen = 76;
nrows = 11;
tfields = 5;
ffitab(fptr, rowlen, nrows, tfields, ttype, tbcol, tform, tunit, tblname,
&status);
printf("ffitab status = %d\n", status);
printf("HDU number = %d\n", ffghdn(fptr, &hdunum));
ffsnul(fptr, 1, "null1", &status); /* define null value for int cols */
ffsnul(fptr, 2, "null2", &status);
ffsnul(fptr, 3, "null3", &status);
ffsnul(fptr, 4, "null4", &status);
ffsnul(fptr, 5, "null5", &status);
extvers = 2;
ffpkyj(fptr, "EXTVER", extvers, "extension version number", &status);
ffpkys(fptr, "TNULL1", "null1", "value for undefined pixels", &status);
ffpkys(fptr, "TNULL2", "null2", "value for undefined pixels", &status);
ffpkys(fptr, "TNULL3", "null3", "value for undefined pixels", &status);
ffpkys(fptr, "TNULL4", "null4", "value for undefined pixels", &status);
ffpkys(fptr, "TNULL5", "null5", "value for undefined pixels", &status);
if (status > 0)
goto errstatus;
/*
############################
# write data to columns #
############################
*/
/* initialize arrays of values to write to table */
for (ii = 0; ii < 21; ii++)
{
boutarray[ii] = (unsigned char) (ii + 1);
ioutarray[ii] = (short) (ii + 1);
joutarray[ii] = ii + 1;
eoutarray[ii] = (float) (ii + 1);
doutarray[ii] = ii + 1;
}
ffpcls(fptr, 1, 1, 1, 3, onskey, &status); /* write string values */
ffpclu(fptr, 1, 4, 1, 1, &status); /* write null value */
for (ii = 2; ii < 6; ii++) /* loop over cols 2 - 5 */
{
ffpclb(fptr, ii, 1, 1, 2, boutarray, &status); /* char array */
if (status == NUM_OVERFLOW)
status = 0;
ffpcli(fptr, ii, 3, 1, 2, &ioutarray[2], &status); /* short array */
if (status == NUM_OVERFLOW)
status = 0;
ffpclj(fptr, ii, 5, 1, 2, &joutarray[4], &status); /* long array */
if (status == NUM_OVERFLOW)
status = 0;
ffpcle(fptr, ii, 7, 1, 2, &eoutarray[6], &status); /* float array */
if (status == NUM_OVERFLOW)
status = 0;
ffpcld(fptr, ii, 9, 1, 2, &doutarray[8], &status); /* double array */
if (status == NUM_OVERFLOW)
status = 0;
ffpclu(fptr, ii, 11, 1, 1, &status); /* write null value */
}
printf("ffpcl_ status = %d\n", status);
/*
################################
# read data from ASCII table #
################################
*/
ffghtb(fptr, 99, &rowlen, &nrows, &tfields, ttype, tbcol,
tform, tunit, tblname, &status);
printf("\nASCII table: rowlen, nrows, tfields, extname: %ld %ld %d %s\n",
rowlen, nrows, tfields, tblname);
for (ii = 0; ii < tfields; ii++)
printf("%8s %3ld %8s %8s \n", ttype[ii], tbcol[ii],
tform[ii], tunit[ii]);
nrows = 11;
ffgcvs(fptr, 1, 1, 1, nrows, "UNDEFINED", inskey, &anynull, &status);
ffgcvb(fptr, 2, 1, 1, nrows, 99, binarray, &anynull, &status);
ffgcvi(fptr, 2, 1, 1, nrows, 99, iinarray, &anynull, &status);
ffgcvj(fptr, 3, 1, 1, nrows, 99, jinarray, &anynull, &status);
ffgcve(fptr, 4, 1, 1, nrows, 99., einarray, &anynull, &status);
ffgcvd(fptr, 5, 1, 1, nrows, 99., dinarray, &anynull, &status);
printf("\nData values read from ASCII table:\n");
for (ii = 0; ii < nrows; ii++)
{
printf("%15s %2d %2d %2ld %4.1f %4.1f\n", inskey[ii], binarray[ii],
iinarray[ii], jinarray[ii], einarray[ii], dinarray[ii]);
}
ffgtbb(fptr, 1, 20, 78, uchars, &status);
uchars[78] = '\0';
printf("\n%s\n", uchars);
ffptbb(fptr, 1, 20, 78, uchars, &status);
/*
#########################################
# get information about the columns #
#########################################
*/
ffgcno(fptr, 0, "name", &colnum, &status);
printf("\nColumn name is number %d; status = %d.\n", colnum, status);
while (status != COL_NOT_FOUND)
{
ffgcnn(fptr, 1, "*ue", colname, &colnum, &status);
printf("Column %s is number %d; status = %d.\n",
colname, colnum, status);
}
status = 0;
for (ii = 0; ii < tfields; ii++)
{
ffgtcl(fptr, ii + 1, &typecode, &repeat, &width, &status);
printf("%4s %3d %2ld %2ld", tform[ii], typecode, repeat, width);
ffgacl(fptr, ii + 1, ttype[0], tbcol, tunit[0], tform[0], &scale,
&zero, nulstr, tdisp, &status);
printf(" %s, %ld, %s, %s, %f, %f, %s, %s.\n",
ttype[0], tbcol[0], tunit[0], tform[0], scale, zero,
nulstr, tdisp);
}
printf("\n");
/*
###############################################
# test the insert/delete row/column routines #
###############################################
*/
if (ffirow(fptr, 2, 3, &status) > 0)
goto errstatus;
nrows = 14;
ffgcvs(fptr, 1, 1, 1, nrows, "UNDEFINED", inskey, &anynull, &status);
ffgcvb(fptr, 2, 1, 1, nrows, 99, binarray, &anynull, &status);
ffgcvi(fptr, 2, 1, 1, nrows, 99, iinarray, &anynull, &status);
ffgcvj(fptr, 3, 1, 1, nrows, 99, jinarray, &anynull, &status);
ffgcve(fptr, 4, 1, 1, nrows, 99., einarray, &anynull, &status);
ffgcvd(fptr, 5, 1, 1, nrows, 99., dinarray, &anynull, &status);
printf("\nData values after inserting 3 rows after row 2:\n");
for (ii = 0; ii < nrows; ii++)
{
printf("%15s %2d %2d %2ld %4.1f %4.1f\n", inskey[ii], binarray[ii],
iinarray[ii], jinarray[ii], einarray[ii], dinarray[ii]);
}
if (ffdrow(fptr, 10, 2, &status) > 0)
goto errstatus;
nrows = 12;
ffgcvs(fptr, 1, 1, 1, nrows, "UNDEFINED", inskey, &anynull, &status);
ffgcvb(fptr, 2, 1, 1, nrows, 99, binarray, &anynull, &status);
ffgcvi(fptr, 2, 1, 1, nrows, 99, iinarray, &anynull, &status);
ffgcvj(fptr, 3, 1, 1, nrows, 99, jinarray, &anynull, &status);
ffgcve(fptr, 4, 1, 1, nrows, 99., einarray, &anynull, &status);
ffgcvd(fptr, 5, 1, 1, nrows, 99., dinarray, &anynull, &status);
printf("\nData values after deleting 2 rows at row 10:\n");
for (ii = 0; ii < nrows; ii++)
{
printf("%15s %2d %2d %2ld %4.1f %4.1f\n", inskey[ii], binarray[ii],
iinarray[ii], jinarray[ii], einarray[ii], dinarray[ii]);
}
if (ffdcol(fptr, 3, &status) > 0)
goto errstatus;
ffgcvs(fptr, 1, 1, 1, nrows, "UNDEFINED", inskey, &anynull, &status);
ffgcvb(fptr, 2, 1, 1, nrows, 99, binarray, &anynull, &status);
ffgcvi(fptr, 2, 1, 1, nrows, 99, iinarray, &anynull, &status);
ffgcve(fptr, 3, 1, 1, nrows, 99., einarray, &anynull, &status);
ffgcvd(fptr, 4, 1, 1, nrows, 99., dinarray, &anynull, &status);
printf("\nData values after deleting column 3:\n");
for (ii = 0; ii < nrows; ii++)
{
printf("%15s %2d %2d %4.1f %4.1f\n", inskey[ii], binarray[ii],
iinarray[ii], einarray[ii], dinarray[ii]);
}
if (fficol(fptr, 5, "INSERT_COL", "F14.6", &status) > 0)
goto errstatus;
ffgcvs(fptr, 1, 1, 1, nrows, "UNDEFINED", inskey, &anynull, &status);
ffgcvb(fptr, 2, 1, 1, nrows, 99, binarray, &anynull, &status);
ffgcvi(fptr, 2, 1, 1, nrows, 99, iinarray, &anynull, &status);
ffgcve(fptr, 3, 1, 1, nrows, 99., einarray, &anynull, &status);
ffgcvd(fptr, 4, 1, 1, nrows, 99., dinarray, &anynull, &status);
ffgcvj(fptr, 5, 1, 1, nrows, 99, jinarray, &anynull, &status);
printf("\nData values after inserting column 5:\n");
for (ii = 0; ii < nrows; ii++)
{
printf("%15s %2d %2d %4.1f %4.1f %ld\n", inskey[ii], binarray[ii],
iinarray[ii], einarray[ii], dinarray[ii] , jinarray[ii]);
}
/*
############################################################
# create a temporary file and copy the ASCII table to it, #
# column by column. #
############################################################
*/
bitpix = 16;
naxis = 0;
strcpy(filename, "!t1q2s3v6.tmp");
ffinit(&tmpfptr, filename, &status);
printf("Create temporary file: ffinit status = %d\n", status);
ffiimg(tmpfptr, bitpix, naxis, naxes, &status);
printf("\nCreate null primary array: ffiimg status = %d\n", status);
/* create an empty table with 12 rows and 0 columns */
nrows = 12;
tfields = 0;
rowlen = 0;
ffitab(tmpfptr, rowlen, nrows, tfields, ttype, tbcol, tform, tunit,
tblname, &status);
printf("\nCreate ASCII table with 0 columns: ffitab status = %d\n",
status);
/* copy columns from one table to the other */
ffcpcl(fptr, tmpfptr, 4, 1, TRUE, &status);
printf("copy column, ffcpcl status = %d\n", status);
ffcpcl(fptr, tmpfptr, 3, 1, TRUE, &status);
printf("copy column, ffcpcl status = %d\n", status);
ffcpcl(fptr, tmpfptr, 2, 1, TRUE, &status);
printf("copy column, ffcpcl status = %d\n", status);
ffcpcl(fptr, tmpfptr, 1, 1, TRUE, &status);
printf("copy column, ffcpcl status = %d\n", status);
/* now repeat by copying ASCII input to Binary output table */
ffibin(tmpfptr, nrows, tfields, ttype, tform, tunit,
tblname, 0L, &status);
printf("\nCreate Binary table with 0 columns: ffibin status = %d\n",
status);
/* copy columns from one table to the other */
ffcpcl(fptr, tmpfptr, 4, 1, TRUE, &status);
printf("copy column, ffcpcl status = %d\n", status);
ffcpcl(fptr, tmpfptr, 3, 1, TRUE, &status);
printf("copy column, ffcpcl status = %d\n", status);
ffcpcl(fptr, tmpfptr, 2, 1, TRUE, &status);
printf("copy column, ffcpcl status = %d\n", status);
ffcpcl(fptr, tmpfptr, 1, 1, TRUE, &status);
printf("copy column, ffcpcl status = %d\n", status);
/*
ffclos(tmpfptr, &status);
printf("Close the tmp file: ffclos status = %d\n", status);
*/
ffdelt(tmpfptr, &status);
printf("Delete the tmp file: ffdelt status = %d\n", status);
if (status > 0)
{
goto errstatus;
}
/*
################################
# read data from binary table #
################################
*/
if (ffmrhd(fptr, 1, &hdutype, &status) > 0)
goto errstatus;
printf("HDU number = %d\n", ffghdn(fptr, &hdunum));
ffghsp(fptr, &existkeys, &morekeys, &status);
printf("header contains %d keywords with room for %d more\n",existkeys,
morekeys);
ffghbn(fptr, 99, &nrows, &tfields, ttype,
tform, tunit, binname, &pcount, &status);
printf("\nBinary table: nrows, tfields, extname, pcount: %ld %d %s %ld\n",
nrows, tfields, binname, pcount);
for (ii = 0; ii < tfields; ii++)
printf("%8s %8s %8s \n", ttype[ii], tform[ii], tunit[ii]);
for (ii = 0; ii < 40; ii++)
larray[ii] = 0;
printf("\nData values read from binary table:\n");
printf(" Bit column (X) data values: \n\n");
ffgcx(fptr, 3, 1, 1, 36, larray, &status);
for (jj = 0; jj < 5; jj++)
{
for (ii = 0; ii < 8; ii++)
printf("%1d",larray[jj * 8 + ii]);
printf(" ");
}
for (ii = 0; ii < nrows; ii++)
{
larray[ii] = 0;
xinarray[ii] = 0;
binarray[ii] = 0;
iinarray[ii] = 0;
kinarray[ii] = 0;
einarray[ii] = 0.;
dinarray[ii] = 0.;
cinarray[ii * 2] = 0.;
minarray[ii * 2] = 0.;
cinarray[ii * 2 + 1] = 0.;
minarray[ii * 2 + 1] = 0.;
}
printf("\n\n");
ffgcvs(fptr, 1, 4, 1, 1, "", inskey, &anynull, &status);
printf("null string column value = -%s- (should be --)\n",inskey[0]);
nrows = 21;
ffgcvs(fptr, 1, 1, 1, nrows, "NOT DEFINED", inskey, &anynull, &status);
ffgcl( fptr, 2, 1, 1, nrows, larray, &status);
ffgcvb(fptr, 3, 1, 1, nrows, 98, xinarray, &anynull, &status);
ffgcvb(fptr, 4, 1, 1, nrows, 98, binarray, &anynull, &status);
ffgcvi(fptr, 5, 1, 1, nrows, 98, iinarray, &anynull, &status);
ffgcvk(fptr, 6, 1, 1, nrows, 98, kinarray, &anynull, &status);
ffgcve(fptr, 7, 1, 1, nrows, 98., einarray, &anynull, &status);
ffgcvd(fptr, 8, 1, 1, nrows, 98., dinarray, &anynull, &status);
ffgcvc(fptr, 9, 1, 1, nrows, 98., cinarray, &anynull, &status);
ffgcvm(fptr, 10, 1, 1, nrows, 98., minarray, &anynull, &status);
printf("\nRead columns with ffgcv_:\n");
for (ii = 0; ii < nrows; ii++)
{
printf("%15s %d %3d %2d %3d %3d %5.1f %5.1f (%5.1f,%5.1f) (%5.1f,%5.1f) \n",
inskey[ii], larray[ii], xinarray[ii], binarray[ii], iinarray[ii],
kinarray[ii], einarray[ii], dinarray[ii], cinarray[ii * 2],
cinarray[ii * 2 + 1], minarray[ii * 2], minarray[ii * 2 + 1]);
}
for (ii = 0; ii < nrows; ii++)
{
larray[ii] = 0;
xinarray[ii] = 0;
binarray[ii] = 0;
iinarray[ii] = 0;
kinarray[ii] = 0;
einarray[ii] = 0.;
dinarray[ii] = 0.;
cinarray[ii * 2] = 0.;
minarray[ii * 2] = 0.;
cinarray[ii * 2 + 1] = 0.;
minarray[ii * 2 + 1] = 0.;
}
ffgcfs(fptr, 1, 1, 1, nrows, inskey, larray2, &anynull, &status);
ffgcfl(fptr, 2, 1, 1, nrows, larray, larray2, &anynull, &status);
ffgcfb(fptr, 3, 1, 1, nrows, xinarray, larray2, &anynull, &status);
ffgcfb(fptr, 4, 1, 1, nrows, binarray, larray2, &anynull, &status);
ffgcfi(fptr, 5, 1, 1, nrows, iinarray, larray2, &anynull, &status);
ffgcfk(fptr, 6, 1, 1, nrows, kinarray, larray2, &anynull, &status);
ffgcfe(fptr, 7, 1, 1, nrows, einarray, larray2, &anynull, &status);
ffgcfd(fptr, 8, 1, 1, nrows, dinarray, larray2, &anynull, &status);
ffgcfc(fptr, 9, 1, 1, nrows, cinarray, larray2, &anynull, &status);
ffgcfm(fptr, 10, 1, 1, nrows, minarray, larray2, &anynull, &status);
printf("\nRead columns with ffgcf_:\n");
for (ii = 0; ii < 10; ii++)
{
printf("%15s %d %3d %2d %3d %3d %5.1f %5.1f (%5.1f,%5.1f) (%5.1f,%5.1f)\n",
inskey[ii], larray[ii], xinarray[ii], binarray[ii], iinarray[ii],
kinarray[ii], einarray[ii], dinarray[ii], cinarray[ii * 2],
cinarray[ii * 2 + 1], minarray[ii * 2], minarray[ii * 2 + 1]);
}
for (ii = 10; ii < nrows; ii++)
{
/* don't try to print the NaN values */
printf("%15s %d %3d %2d %3d \n",
inskey[ii], larray[ii], xinarray[ii], binarray[ii], iinarray[ii]);
}
ffprec(fptr,
"key_prec= 'This keyword was written by f_prec' / comment here", &status);
/*
###############################################
# test the insert/delete row/column routines #
###############################################
*/
if (ffirow(fptr, 2, 3, &status) > 0)
goto errstatus;
nrows = 14;
ffgcvs(fptr, 1, 1, 1, nrows, "NOT DEFINED", inskey, &anynull, &status);
ffgcvb(fptr, 4, 1, 1, nrows, 98, binarray, &anynull, &status);
ffgcvi(fptr, 5, 1, 1, nrows, 98, iinarray, &anynull, &status);
ffgcvj(fptr, 6, 1, 1, nrows, 98, jinarray, &anynull, &status);
ffgcve(fptr, 7, 1, 1, nrows, 98., einarray, &anynull, &status);
ffgcvd(fptr, 8, 1, 1, nrows, 98., dinarray, &anynull, &status);
printf("\nData values after inserting 3 rows after row 2:\n");
for (ii = 0; ii < nrows; ii++)
{
printf("%15s %2d %3d %3ld %5.1f %5.1f\n", inskey[ii], binarray[ii],
iinarray[ii], jinarray[ii], einarray[ii], dinarray[ii]);
}
if (ffdrow(fptr, 10, 2, &status) > 0)
goto errstatus;
nrows = 12;
ffgcvs(fptr, 1, 1, 1, nrows, "NOT DEFINED", inskey, &anynull, &status);
ffgcvb(fptr, 4, 1, 1, nrows, 98, binarray, &anynull, &status);
ffgcvi(fptr, 5, 1, 1, nrows, 98, iinarray, &anynull, &status);
ffgcvj(fptr, 6, 1, 1, nrows, 98, jinarray, &anynull, &status);
ffgcve(fptr, 7, 1, 1, nrows, 98., einarray, &anynull, &status);
ffgcvd(fptr, 8, 1, 1, nrows, 98., dinarray, &anynull, &status);
printf("\nData values after deleting 2 rows at row 10:\n");
for (ii = 0; ii < nrows; ii++)
{
printf("%15s %2d %3d %3ld %5.1f %5.1f\n", inskey[ii], binarray[ii],
iinarray[ii], jinarray[ii], einarray[ii], dinarray[ii]);
}
if (ffdcol(fptr, 6, &status) > 0)
goto errstatus;
ffgcvs(fptr, 1, 1, 1, nrows, "NOT DEFINED", inskey, &anynull, &status);
ffgcvb(fptr, 4, 1, 1, nrows, 98, binarray, &anynull, &status);
ffgcvi(fptr, 5, 1, 1, nrows, 98, iinarray, &anynull, &status);
ffgcve(fptr, 6, 1, 1, nrows, 98., einarray, &anynull, &status);
ffgcvd(fptr, 7, 1, 1, nrows, 98., dinarray, &anynull, &status);
printf("\nData values after deleting column 6:\n");
for (ii = 0; ii < nrows; ii++)
{
printf("%15s %2d %3d %5.1f %5.1f\n", inskey[ii], binarray[ii],
iinarray[ii], einarray[ii], dinarray[ii]);
}
if (fficol(fptr, 8, "INSERT_COL", "1E", &status) > 0)
goto errstatus;
ffgcvs(fptr, 1, 1, 1, nrows, "NOT DEFINED", inskey, &anynull, &status);
ffgcvb(fptr, 4, 1, 1, nrows, 98, binarray, &anynull, &status);
ffgcvi(fptr, 5, 1, 1, nrows, 98, iinarray, &anynull, &status);
ffgcve(fptr, 6, 1, 1, nrows, 98., einarray, &anynull, &status);
ffgcvd(fptr, 7, 1, 1, nrows, 98., dinarray, &anynull, &status);
ffgcvj(fptr, 8, 1, 1, nrows, 98, jinarray, &anynull, &status);
printf("\nData values after inserting column 8:\n");
for (ii = 0; ii < nrows; ii++)
{
printf("%15s %2d %3d %5.1f %5.1f %ld\n", inskey[ii], binarray[ii],
iinarray[ii], einarray[ii], dinarray[ii] , jinarray[ii]);
}
ffpclu(fptr, 8, 1, 1, 10, &status);
ffgcvs(fptr, 1, 1, 1, nrows, "NOT DEFINED", inskey, &anynull, &status);
ffgcvb(fptr, 4, 1, 1, nrows, 98, binarray, &anynull, &status);
ffgcvi(fptr, 5, 1, 1, nrows, 98, iinarray, &anynull, &status);
ffgcve(fptr, 6, 1, 1, nrows, 98., einarray, &anynull, &status);
ffgcvd(fptr, 7, 1, 1, nrows, 98., dinarray, &anynull, &status);
ffgcvj(fptr, 8, 1, 1, nrows, 98, jinarray, &anynull, &status);
printf("\nValues after setting 1st 10 elements in column 8 = null:\n");
for (ii = 0; ii < nrows; ii++)
{
printf("%15s %2d %3d %5.1f %5.1f %ld\n", inskey[ii], binarray[ii],
iinarray[ii], einarray[ii], dinarray[ii] , jinarray[ii]);
}
/*
############################################################
# create a temporary file and copy the binary table to it,#
# column by column. #
############################################################
*/
bitpix = 16;
naxis = 0;
strcpy(filename, "!t1q2s3v5.tmp");
ffinit(&tmpfptr, filename, &status);
printf("Create temporary file: ffinit status = %d\n", status);
ffiimg(tmpfptr, bitpix, naxis, naxes, &status);
printf("\nCreate null primary array: ffiimg status = %d\n", status);
/* create an empty table with 22 rows and 0 columns */
nrows = 22;
tfields = 0;
ffibin(tmpfptr, nrows, tfields, ttype, tform, tunit, binname, 0L,
&status);
printf("\nCreate binary table with 0 columns: ffibin status = %d\n",
status);
/* copy columns from one table to the other */
ffcpcl(fptr, tmpfptr, 7, 1, TRUE, &status);
printf("copy column, ffcpcl status = %d\n", status);
ffcpcl(fptr, tmpfptr, 6, 1, TRUE, &status);
printf("copy column, ffcpcl status = %d\n", status);
ffcpcl(fptr, tmpfptr, 5, 1, TRUE, &status);
printf("copy column, ffcpcl status = %d\n", status);
ffcpcl(fptr, tmpfptr, 4, 1, TRUE, &status);
printf("copy column, ffcpcl status = %d\n", status);
ffcpcl(fptr, tmpfptr, 3, 1, TRUE, &status);
printf("copy column, ffcpcl status = %d\n", status);
ffcpcl(fptr, tmpfptr, 2, 1, TRUE, &status);
printf("copy column, ffcpcl status = %d\n", status);
ffcpcl(fptr, tmpfptr, 1, 1, TRUE, &status);
printf("copy column, ffcpcl status = %d\n", status);
/*
ffclos(tmpfptr, &status);
printf("Close the tmp file: ffclos status = %d\n", status);
*/
ffdelt(tmpfptr, &status);
printf("Delete the tmp file: ffdelt status = %d\n", status);
if (status > 0)
{
goto errstatus;
}
/*
####################################################
# insert binary table following the primary array #
####################################################
*/
ffmahd(fptr, 1, &hdutype, &status);
strcpy(tform[0], "15A");
strcpy(tform[1], "1L");
strcpy(tform[2], "16X");
strcpy(tform[3], "1B");
strcpy(tform[4], "1I");
strcpy(tform[5], "1J");
strcpy(tform[6], "1E");
strcpy(tform[7], "1D");
strcpy(tform[8], "1C");
strcpy(tform[9], "1M");
strcpy(ttype[0], "Avalue");
strcpy(ttype[1], "Lvalue");
strcpy(ttype[2], "Xvalue");
strcpy(ttype[3], "Bvalue");
strcpy(ttype[4], "Ivalue");
strcpy(ttype[5], "Jvalue");
strcpy(ttype[6], "Evalue");
strcpy(ttype[7], "Dvalue");
strcpy(ttype[8], "Cvalue");
strcpy(ttype[9], "Mvalue");
strcpy(tunit[0], "");
strcpy(tunit[1], "m**2");
strcpy(tunit[2], "cm");
strcpy(tunit[3], "erg/s");
strcpy(tunit[4], "km/s");
strcpy(tunit[5], "");
strcpy(tunit[6], "");
strcpy(tunit[7], "");
strcpy(tunit[8], "");
strcpy(tunit[9], "");
nrows = 20;
tfields = 10;
pcount = 0;
ffibin(fptr, nrows, tfields, ttype, tform, tunit, binname, pcount,
&status);
printf("ffibin status = %d\n", status);
printf("HDU number = %d\n", ffghdn(fptr, &hdunum));
extvers = 3;
ffpkyj(fptr, "EXTVER", extvers, "extension version number", &status);
ffpkyj(fptr, "TNULL4", 77, "value for undefined pixels", &status);
ffpkyj(fptr, "TNULL5", 77, "value for undefined pixels", &status);
ffpkyj(fptr, "TNULL6", 77, "value for undefined pixels", &status);
ffpkyj(fptr, "TSCAL4", 1000, "scaling factor", &status);
ffpkyj(fptr, "TSCAL5", 1, "scaling factor", &status);
ffpkyj(fptr, "TSCAL6", 100, "scaling factor", &status);
ffpkyj(fptr, "TZERO4", 0, "scaling offset", &status);
ffpkyj(fptr, "TZERO5", 32768, "scaling offset", &status);
ffpkyj(fptr, "TZERO6", 100, "scaling offset", &status);
fftnul(fptr, 4, 77, &status); /* define null value for int cols */
fftnul(fptr, 5, 77, &status);
fftnul(fptr, 6, 77, &status);
/* set scaling */
fftscl(fptr, 4, 1000., 0., &status);
fftscl(fptr, 5, 1., 32768., &status);
fftscl(fptr, 6, 100., 100., &status);
/*
############################
# write data to columns #
############################
*/
/* initialize arrays of values to write to table */
joutarray[0] = 0;
joutarray[1] = 1000;
joutarray[2] = 10000;
joutarray[3] = 32768;
joutarray[4] = 65535;
for (ii = 4; ii < 7; ii++)
{
ffpclj(fptr, ii, 1, 1, 5, joutarray, &status);
if (status == NUM_OVERFLOW)
{
printf("Overflow writing to column %ld\n", ii);
status = 0;
}
ffpclu(fptr, ii, 6, 1, 1, &status); /* write null value */
}
for (jj = 4; jj < 7; jj++)
{
ffgcvj(fptr, jj, 1, 1, 6, -999, jinarray, &anynull, &status);
for (ii = 0; ii < 6; ii++)
{
printf(" %6ld", jinarray[ii]);
}
printf("\n");
}
printf("\n");
/* turn off scaling, and read the unscaled values */
fftscl(fptr, 4, 1., 0., &status);
fftscl(fptr, 5, 1., 0., &status);
fftscl(fptr, 6, 1., 0., &status);
for (jj = 4; jj < 7; jj++)
{
ffgcvj(fptr, jj, 1, 1, 6, -999, jinarray, &anynull, &status);
for (ii = 0; ii < 6; ii++)
{
printf(" %6ld", jinarray[ii]);
}
printf("\n");
}
/*
######################################################
# insert image extension following the binary table #
######################################################
*/
bitpix = -32;
naxis = 2;
naxes[0] = 15;
naxes[1] = 25;
ffiimg(fptr, bitpix, naxis, naxes, &status);
printf("\nCreate image extension: ffiimg status = %d\n", status);
printf("HDU number = %d\n", ffghdn(fptr, &hdunum));
for (jj = 0; jj < 30; jj++)
{
for (ii = 0; ii < 19; ii++)
{
imgarray[jj][ii] = (short) ((jj * 10) + ii);
}
}
ffp2di(fptr, 1, 19, naxes[0], naxes[1], imgarray[0], &status);
printf("\nWrote whole 2D array: ffp2di status = %d\n", status);
for (jj = 0; jj < 30; jj++)
{
for (ii = 0; ii < 19; ii++)
{
imgarray[jj][ii] = 0;
}
}
ffg2di(fptr, 1, 0, 19, naxes[0], naxes[1], imgarray[0], &anynull,
&status);
printf("\nRead whole 2D array: ffg2di status = %d\n", status);
for (jj = 0; jj < 30; jj++)
{
for (ii = 0; ii < 19; ii++)
{
printf(" %3d", imgarray[jj][ii]);
}
printf("\n");
}
for (jj = 0; jj < 30; jj++)
{
for (ii = 0; ii < 19; ii++)
{
imgarray[jj][ii] = 0;
}
}
for (jj = 0; jj < 20; jj++)
{
for (ii = 0; ii < 10; ii++)
{
imgarray2[jj][ii] = (short) ((jj * -10) - ii);
}
}
fpixels[0] = 5;
fpixels[1] = 5;
lpixels[0] = 14;
lpixels[1] = 14;
ffpssi(fptr, 1, naxis, naxes, fpixels, lpixels,
imgarray2[0], &status);
printf("\nWrote subset 2D array: ffpssi status = %d\n", status);
ffg2di(fptr, 1, 0, 19, naxes[0], naxes[1], imgarray[0], &anynull,
&status);
printf("\nRead whole 2D array: ffg2di status = %d\n", status);
for (jj = 0; jj < 30; jj++)
{
for (ii = 0; ii < 19; ii++)
{
printf(" %3d", imgarray[jj][ii]);
}
printf("\n");
}
fpixels[0] = 2;
fpixels[1] = 5;
lpixels[0] = 10;
lpixels[1] = 8;
inc[0] = 2;
inc[1] = 3;
for (jj = 0; jj < 30; jj++)
{
for (ii = 0; ii < 19; ii++)
{
imgarray[jj][ii] = 0;
}
}
ffgsvi(fptr, 1, naxis, naxes, fpixels, lpixels, inc, 0,
imgarray[0], &anynull, &status);
printf("\nRead subset of 2D array: ffgsvi status = %d\n", status);
for (ii = 0; ii < 10; ii++)
{
printf(" %3d", imgarray[0][ii]);
}
printf("\n");
/*
###########################################################
# insert another image extension #
# copy the image extension to primary array of tmp file. #
# then delete the tmp file, and the image extension #
###########################################################
*/
bitpix = 16;
naxis = 2;
naxes[0] = 15;
naxes[1] = 25;
ffiimg(fptr, bitpix, naxis, naxes, &status);
printf("\nCreate image extension: ffiimg status = %d\n", status);
printf("HDU number = %d\n", ffghdn(fptr, &hdunum));
strcpy(filename, "t1q2s3v4.tmp");
ffinit(&tmpfptr, filename, &status);
printf("Create temporary file: ffinit status = %d\n", status);
ffcopy(fptr, tmpfptr, 0, &status);
printf("Copy image extension to primary array of tmp file.\n");
printf("ffcopy status = %d\n", status);
ffgrec(tmpfptr, 1, card, &status);
printf("%s\n", card);
ffgrec(tmpfptr, 2, card, &status);
printf("%s\n", card);
ffgrec(tmpfptr, 3, card, &status);
printf("%s\n", card);
ffgrec(tmpfptr, 4, card, &status);
printf("%s\n", card);
ffgrec(tmpfptr, 5, card, &status);
printf("%s\n", card);
ffgrec(tmpfptr, 6, card, &status);
printf("%s\n", card);
ffdelt(tmpfptr, &status);
printf("Delete the tmp file: ffdelt status = %d\n", status);
ffdhdu(fptr, &hdutype, &status);
printf("Delete the image extension; hdutype, status = %d %d\n",
hdutype, status);
printf("HDU number = %d\n", ffghdn(fptr, &hdunum));
/*
###########################################################
# append bintable extension with variable length columns #
###########################################################
*/
ffcrhd(fptr, &status);
printf("ffcrhd status = %d\n", status);
strcpy(tform[0], "1PA");
strcpy(tform[1], "1PL");
strcpy(tform[2], "1PB"); /* Fortran FITSIO doesn't support 1PX */
strcpy(tform[3], "1PB");
strcpy(tform[4], "1PI");
strcpy(tform[5], "1PJ");
strcpy(tform[6], "1PE");
strcpy(tform[7], "1PD");
strcpy(tform[8], "1PC");
strcpy(tform[9], "1PM");
strcpy(ttype[0], "Avalue");
strcpy(ttype[1], "Lvalue");
strcpy(ttype[2], "Xvalue");
strcpy(ttype[3], "Bvalue");
strcpy(ttype[4], "Ivalue");
strcpy(ttype[5], "Jvalue");
strcpy(ttype[6], "Evalue");
strcpy(ttype[7], "Dvalue");
strcpy(ttype[8], "Cvalue");
strcpy(ttype[9], "Mvalue");
strcpy(tunit[0], "");
strcpy(tunit[1], "m**2");
strcpy(tunit[2], "cm");
strcpy(tunit[3], "erg/s");
strcpy(tunit[4], "km/s");
strcpy(tunit[5], "");
strcpy(tunit[6], "");
strcpy(tunit[7], "");
strcpy(tunit[8], "");
strcpy(tunit[9], "");
nrows = 20;
tfields = 10;
pcount = 0;
ffphbn(fptr, nrows, tfields, ttype, tform, tunit, binname, pcount,
&status);
printf("Variable length arrays: ffphbn status = %d\n", status);
extvers = 4;
ffpkyj(fptr, "EXTVER", extvers, "extension version number", &status);
ffpkyj(fptr, "TNULL4", 88, "value for undefined pixels", &status);
ffpkyj(fptr, "TNULL5", 88, "value for undefined pixels", &status);
ffpkyj(fptr, "TNULL6", 88, "value for undefined pixels", &status);
/*
############################
# write data to columns #
############################
*/
/* initialize arrays of values to write to table */
strcpy(iskey,"abcdefghijklmnopqrst");
for (ii = 0; ii < 20; ii++)
{
boutarray[ii] = (unsigned char) (ii + 1);
ioutarray[ii] = (short) (ii + 1);
joutarray[ii] = ii + 1;
eoutarray[ii] = (float) (ii + 1);
doutarray[ii] = ii + 1;
}
larray[0] = 0;
larray[1] = 1;
larray[2] = 0;
larray[3] = 0;
larray[4] = 1;
larray[5] = 1;
larray[6] = 0;
larray[7] = 0;
larray[8] = 0;
larray[9] = 1;
larray[10] = 1;
larray[11] = 1;
larray[12] = 0;
larray[13] = 0;
larray[14] = 0;
larray[15] = 0;
larray[16] = 1;
larray[17] = 1;
larray[18] = 1;
larray[19] = 1;
/* write values in 1st row */
/* strncpy(inskey[0], iskey, 1); */
inskey[0][0] = '\0'; /* write a null string (i.e., a blank) */
ffpcls(fptr, 1, 1, 1, 1, inskey, &status); /* write string values */
ffpcll(fptr, 2, 1, 1, 1, larray, &status); /* write logicals */
ffpclx(fptr, 3, 1, 1, 1, larray, &status); /* write bits */
ffpclb(fptr, 4, 1, 1, 1, boutarray, &status);
ffpcli(fptr, 5, 1, 1, 1, ioutarray, &status);
ffpclj(fptr, 6, 1, 1, 1, joutarray, &status);
ffpcle(fptr, 7, 1, 1, 1, eoutarray, &status);
ffpcld(fptr, 8, 1, 1, 1, doutarray, &status);
for (ii = 2; ii <= 20; ii++) /* loop over rows 1 - 20 */
{
strncpy(inskey[0], iskey, ii);
inskey[0][ii] = '\0';
ffpcls(fptr, 1, ii, 1, 1, inskey, &status); /* write string values */
ffpcll(fptr, 2, ii, 1, ii, larray, &status); /* write logicals */
ffpclu(fptr, 2, ii, ii-1, 1, &status);
ffpclx(fptr, 3, ii, 1, ii, larray, &status); /* write bits */
ffpclb(fptr, 4, ii, 1, ii, boutarray, &status);
ffpclu(fptr, 4, ii, ii-1, 1, &status);
ffpcli(fptr, 5, ii, 1, ii, ioutarray, &status);
ffpclu(fptr, 5, ii, ii-1, 1, &status);
ffpclj(fptr, 6, ii, 1, ii, joutarray, &status);
ffpclu(fptr, 6, ii, ii-1, 1, &status);
ffpcle(fptr, 7, ii, 1, ii, eoutarray, &status);
ffpclu(fptr, 7, ii, ii-1, 1, &status);
ffpcld(fptr, 8, ii, 1, ii, doutarray, &status);
ffpclu(fptr, 8, ii, ii-1, 1, &status);
}
printf("ffpcl_ status = %d\n", status);
/*
#################################
# close then reopen this HDU #
#################################
*/
ffmrhd(fptr, -1, &hdutype, &status);
ffmrhd(fptr, 1, &hdutype, &status);
/*
#############################
# read data from columns #
#############################
*/
ffgkyj(fptr, "PCOUNT", &pcount, comm, &status);
printf("PCOUNT = %ld\n", pcount);
/* initialize the variables to be read */
strcpy(inskey[0]," ");
strcpy(iskey," ");
printf("HDU number = %d\n", ffghdn(fptr, &hdunum));
for (ii = 1; ii <= 20; ii++) /* loop over rows 1 - 20 */
{
for (jj = 0; jj < ii; jj++)
{
larray[jj] = 0;
boutarray[jj] = 0;
ioutarray[jj] = 0;
joutarray[jj] = 0;
eoutarray[jj] = 0;
doutarray[jj] = 0;
}
ffgcvs(fptr, 1, ii, 1, 1, iskey, inskey, &anynull, &status);
printf("A %s %d\nL", inskey[0], status);
ffgcl( fptr, 2, ii, 1, ii, larray, &status);
for (jj = 0; jj < ii; jj++)
printf(" %2d", larray[jj]);
printf(" %d\nX", status);
ffgcx(fptr, 3, ii, 1, ii, larray, &status);
for (jj = 0; jj < ii; jj++)
printf(" %2d", larray[jj]);
printf(" %d\nB", status);
ffgcvb(fptr, 4, ii, 1, ii, 99, boutarray, &anynull, &status);
for (jj = 0; jj < ii; jj++)
printf(" %2d", boutarray[jj]);
printf(" %d\nI", status);
ffgcvi(fptr, 5, ii, 1, ii, 99, ioutarray, &anynull, &status);
for (jj = 0; jj < ii; jj++)
printf(" %2d", ioutarray[jj]);
printf(" %d\nJ", status);
ffgcvj(fptr, 6, ii, 1, ii, 99, joutarray, &anynull, &status);
for (jj = 0; jj < ii; jj++)
printf(" %2ld", joutarray[jj]);
printf(" %d\nE", status);
ffgcve(fptr, 7, ii, 1, ii, 99., eoutarray, &anynull, &status);
for (jj = 0; jj < ii; jj++)
printf(" %2.0f", eoutarray[jj]);
printf(" %d\nD", status);
ffgcvd(fptr, 8, ii, 1, ii, 99., doutarray, &anynull, &status);
for (jj = 0; jj < ii; jj++)
printf(" %2.0f", doutarray[jj]);
printf(" %d\n", status);
ffgdes(fptr, 8, ii, &repeat, &offset, &status);
printf("Column 8 repeat and offset = %ld %ld\n", repeat, offset);
}
/*
#####################################
# create another image extension #
#####################################
*/
bitpix = 32;
naxis = 2;
naxes[0] = 10;
naxes[1] = 2;
npixels = 20;
/* ffcrim(fptr, bitpix, naxis, naxes, &status); */
ffiimg(fptr, bitpix, naxis, naxes, &status);
printf("\nffcrim status = %d\n", status);
/* initialize arrays of values to write to primary array */
for (ii = 0; ii < npixels; ii++)
{
boutarray[ii] = (unsigned char) (ii * 2);
ioutarray[ii] = (short) (ii * 2);
joutarray[ii] = ii * 2;
koutarray[ii] = ii * 2;
eoutarray[ii] = (float) (ii * 2);
doutarray[ii] = ii * 2;
}
/* write a few pixels with each datatype */
ffppr(fptr, TBYTE, 1, 2, &boutarray[0], &status);
ffppr(fptr, TSHORT, 3, 2, &ioutarray[2], &status);
ffppr(fptr, TINT, 5, 2, &koutarray[4], &status);
ffppr(fptr, TSHORT, 7, 2, &ioutarray[6], &status);
ffppr(fptr, TLONG, 9, 2, &joutarray[8], &status);
ffppr(fptr, TFLOAT, 11, 2, &eoutarray[10], &status);
ffppr(fptr, TDOUBLE, 13, 2, &doutarray[12], &status);
printf("ffppr status = %d\n", status);
/* read back the pixels with each datatype */
bnul = 0;
inul = 0;
knul = 0;
jnul = 0;
enul = 0.;
dnul = 0.;
ffgpv(fptr, TBYTE, 1, 14, &bnul, binarray, &anynull, &status);
ffgpv(fptr, TSHORT, 1, 14, &inul, iinarray, &anynull, &status);
ffgpv(fptr, TINT, 1, 14, &knul, kinarray, &anynull, &status);
ffgpv(fptr, TLONG, 1, 14, &jnul, jinarray, &anynull, &status);
ffgpv(fptr, TFLOAT, 1, 14, &enul, einarray, &anynull, &status);
ffgpv(fptr, TDOUBLE, 1, 14, &dnul, dinarray, &anynull, &status);
printf("\nImage values written with ffppr and read with ffgpv:\n");
npixels = 14;
for (ii = 0; ii < npixels; ii++)
printf(" %2d", binarray[ii]);
printf(" %d (byte)\n", anynull);
for (ii = 0; ii < npixels; ii++)
printf(" %2d", iinarray[ii]);
printf(" %d (short)\n", anynull);
for (ii = 0; ii < npixels; ii++)
printf(" %2d", kinarray[ii]);
printf(" %d (int)\n", anynull);
for (ii = 0; ii < npixels; ii++)
printf(" %2ld", jinarray[ii]);
printf(" %d (long)\n", anynull);
for (ii = 0; ii < npixels; ii++)
printf(" %2.0f", einarray[ii]);
printf(" %d (float)\n", anynull);
for (ii = 0; ii < npixels; ii++)
printf(" %2.0f", dinarray[ii]);
printf(" %d (double)\n", anynull);
/*
##########################################
# test world coordinate system routines #
##########################################
*/
xrval = 45.83;
yrval = 63.57;
xrpix = 256.;
yrpix = 257.;
xinc = -.00277777;
yinc = .00277777;
/* write the WCS keywords */
/* use example values from the latest WCS document */
ffpkyd(fptr, "CRVAL1", xrval, 10, "comment", &status);
ffpkyd(fptr, "CRVAL2", yrval, 10, "comment", &status);
ffpkyd(fptr, "CRPIX1", xrpix, 10, "comment", &status);
ffpkyd(fptr, "CRPIX2", yrpix, 10, "comment", &status);
ffpkyd(fptr, "CDELT1", xinc, 10, "comment", &status);
ffpkyd(fptr, "CDELT2", yinc, 10, "comment", &status);
/* ffpkyd(fptr, "CROTA2", rot, 10, "comment", &status); */
ffpkys(fptr, "CTYPE1", xcoordtype, "comment", &status);
ffpkys(fptr, "CTYPE2", ycoordtype, "comment", &status);
printf("\nWrote WCS keywords status = %d\n",status);
xrval = 0.;
yrval = 0.;
xrpix = 0.;
yrpix = 0.;
xinc = 0.;
yinc = 0.;
rot = 0.;
ffgics(fptr, &xrval, &yrval, &xrpix,
&yrpix, &xinc, &yinc, &rot, ctype, &status);
printf("Read WCS keywords with ffgics status = %d\n",status);
xpix = 0.5;
ypix = 0.5;
ffwldp(xpix,ypix,xrval,yrval,xrpix,yrpix,xinc,yinc,rot,ctype,
&xpos, &ypos,&status);
printf(" CRVAL1, CRVAL2 = %16.12f, %16.12f\n", xrval,yrval);
printf(" CRPIX1, CRPIX2 = %16.12f, %16.12f\n", xrpix,yrpix);
printf(" CDELT1, CDELT2 = %16.12f, %16.12f\n", xinc,yinc);
printf(" Rotation = %10.3f, CTYPE = %s\n", rot, ctype);
printf("Calculated sky coordinate with ffwldp status = %d\n",status);
printf(" Pixels (%8.4f,%8.4f) --> (%11.6f, %11.6f) Sky\n",
xpix,ypix,xpos,ypos);
ffxypx(xpos,ypos,xrval,yrval,xrpix,yrpix,xinc,yinc,rot,ctype,
&xpix, &ypix,&status);
printf("Calculated pixel coordinate with ffxypx status = %d\n",status);
printf(" Sky (%11.6f, %11.6f) --> (%8.4f,%8.4f) Pixels\n",
xpos,ypos,xpix,ypix);
/*
######################################
# append another ASCII table #
######################################
*/
strcpy(tform[0], "A15");
strcpy(tform[1], "I11");
strcpy(tform[2], "F15.6");
strcpy(tform[3], "E13.5");
strcpy(tform[4], "D22.14");
strcpy(ttype[0], "Name");
strcpy(ttype[1], "Ivalue");
strcpy(ttype[2], "Fvalue");
strcpy(ttype[3], "Evalue");
strcpy(ttype[4], "Dvalue");
strcpy(tunit[0], "");
strcpy(tunit[1], "m**2");
strcpy(tunit[2], "cm");
strcpy(tunit[3], "erg/s");
strcpy(tunit[4], "km/s");
nrows = 11;
tfields = 5;
strcpy(tblname, "new_table");
ffcrtb(fptr, ASCII_TBL, nrows, tfields, ttype, tform, tunit, tblname,
&status);
printf("\nffcrtb status = %d\n", status);
extvers = 5;
ffpkyj(fptr, "EXTVER", extvers, "extension version number", &status);
ffpcl(fptr, TSTRING, 1, 1, 1, 3, onskey, &status); /* write string values */
/* initialize arrays of values to write */
for (ii = 0; ii < npixels; ii++)
{
boutarray[ii] = (unsigned char) (ii * 3);
ioutarray[ii] = (short) (ii * 3);
joutarray[ii] = ii * 3;
koutarray[ii] = ii * 3;
eoutarray[ii] = (float) (ii * 3);
doutarray[ii] = ii * 3;
}
for (ii = 2; ii < 6; ii++) /* loop over cols 2 - 5 */
{
ffpcl(fptr, TBYTE, ii, 1, 1, 2, boutarray, &status);
ffpcl(fptr, TSHORT, ii, 3, 1, 2, &ioutarray[2], &status);
ffpcl(fptr, TLONG, ii, 5, 1, 2, &joutarray[4], &status);
ffpcl(fptr, TFLOAT, ii, 7, 1, 2, &eoutarray[6], &status);
ffpcl(fptr, TDOUBLE, ii, 9, 1, 2, &doutarray[8], &status);
}
printf("ffpcl status = %d\n", status);
/* read back the pixels with each datatype */
ffgcv(fptr, TBYTE, 2, 1, 1, 10, &bnul, binarray, &anynull, &status);
ffgcv(fptr, TSHORT, 2, 1, 1, 10, &inul, iinarray, &anynull, &status);
ffgcv(fptr, TINT, 3, 1, 1, 10, &knul, kinarray, &anynull, &status);
ffgcv(fptr, TLONG, 3, 1, 1, 10, &jnul, jinarray, &anynull, &status);
ffgcv(fptr, TFLOAT, 4, 1, 1, 10, &enul, einarray, &anynull, &status);
ffgcv(fptr, TDOUBLE, 5, 1, 1, 10, &dnul, dinarray, &anynull, &status);
printf("\nColumn values written with ffpcl and read with ffgcl:\n");
npixels = 10;
for (ii = 0; ii < npixels; ii++)
printf(" %2d", binarray[ii]);
printf(" %d (byte)\n", anynull);
for (ii = 0; ii < npixels; ii++)
printf(" %2d", iinarray[ii]);
printf(" %d (short)\n", anynull);
for (ii = 0; ii < npixels; ii++)
printf(" %2d", kinarray[ii]);
printf(" %d (int)\n", anynull);
for (ii = 0; ii < npixels; ii++)
printf(" %2ld", jinarray[ii]);
printf(" %d (long)\n", anynull);
for (ii = 0; ii < npixels; ii++)
printf(" %2.0f", einarray[ii]);
printf(" %d (float)\n", anynull);
for (ii = 0; ii < npixels; ii++)
printf(" %2.0f", dinarray[ii]);
printf(" %d (double)\n", anynull);
/*
###########################################################
# perform stress test by cycling thru all the extensions #
###########################################################
*/
printf("\nRepeatedly move to the 1st 4 HDUs of the file:\n");
for (ii = 0; ii < 10; ii++)
{
ffmahd(fptr, 1, &hdutype, &status);
printf("%d", ffghdn(fptr, &hdunum));
ffmrhd(fptr, 1, &hdutype, &status);
printf("%d", ffghdn(fptr, &hdunum));
ffmrhd(fptr, 1, &hdutype, &status);
printf("%d", ffghdn(fptr, &hdunum));
ffmrhd(fptr, 1, &hdutype, &status);
printf("%d", ffghdn(fptr, &hdunum));
ffmrhd(fptr, -1, &hdutype, &status);
printf("%d", ffghdn(fptr, &hdunum));
if (status > 0)
break;
}
printf("\n");
printf("Move to extensions by name and version number: (ffmnhd)\n");
extvers = 1;
ffmnhd(fptr, ANY_HDU, binname, (int) extvers, &status);
ffghdn(fptr, &hdunum);
printf(" %s, %ld = hdu %d, %d\n", binname, extvers, hdunum, status);
extvers = 3;
ffmnhd(fptr, ANY_HDU, binname, (int) extvers, &status);
ffghdn(fptr, &hdunum);
printf(" %s, %ld = hdu %d, %d\n", binname, extvers, hdunum, status);
extvers = 4;
ffmnhd(fptr, ANY_HDU, binname, (int) extvers, &status);
ffghdn(fptr, &hdunum);
printf(" %s, %ld = hdu %d, %d\n", binname, extvers, hdunum, status);
strcpy(tblname, "Test-ASCII");
extvers = 2;
ffmnhd(fptr, ANY_HDU, tblname, (int) extvers, &status);
ffghdn(fptr, &hdunum);
printf(" %s, %ld = hdu %d, %d\n", tblname, extvers, hdunum, status);
strcpy(tblname, "new_table");
extvers = 5;
ffmnhd(fptr, ANY_HDU, tblname, (int) extvers, &status);
ffghdn(fptr, &hdunum);
printf(" %s, %ld = hdu %d, %d\n", tblname, extvers, hdunum, status);
extvers = 0;
ffmnhd(fptr, ANY_HDU, binname, (int) extvers, &status);
ffghdn(fptr, &hdunum);
printf(" %s, %ld = hdu %d, %d\n", binname, extvers, hdunum, status);
extvers = 17;
ffmnhd(fptr, ANY_HDU, binname, (int) extvers, &status);
ffghdn(fptr, &hdunum);
printf(" %s, %ld = hdu %d, %d", binname, extvers, hdunum, status);
printf (" (expect a 301 error status here)\n");
status = 0;
ffthdu(fptr, &hdunum, &status);
printf("Total number of HDUs in the file = %d\n", hdunum);
/*
########################
# checksum tests #
########################
*/
checksum = 1234567890;
ffesum(checksum, 0, asciisum);
printf("\nEncode checksum: %lu -> %s\n", checksum, asciisum);
checksum = 0;
ffdsum(asciisum, 0, &checksum);
printf("Decode checksum: %s -> %lu\n", asciisum, checksum);
ffpcks(fptr, &status);
/*
don't print the CHECKSUM value because it is different every day
because the current date is in the comment field.
ffgcrd(fptr, "CHECKSUM", card, &status);
printf("%s\n", card);
*/
ffgcrd(fptr, "DATASUM", card, &status);
printf("%.30s\n", card);
ffgcks(fptr, &datsum, &checksum, &status);
printf("ffgcks data checksum, status = %lu, %d\n",
datsum, status);
ffvcks(fptr, &datastatus, &hdustatus, &status);
printf("ffvcks datastatus, hdustatus, status = %d %d %d\n",
datastatus, hdustatus, status);
ffprec(fptr,
"new_key = 'written by fxprec' / to change checksum", &status);
ffupck(fptr, &status);
printf("ffupck status = %d\n", status);
ffgcrd(fptr, "DATASUM", card, &status);
printf("%.30s\n", card);
ffvcks(fptr, &datastatus, &hdustatus, &status);
printf("ffvcks datastatus, hdustatus, status = %d %d %d\n",
datastatus, hdustatus, status);
/*
delete the checksum keywords, so that the FITS file is always
the same, regardless of the date of when testprog is run.
*/
ffdkey(fptr, "CHECKSUM", &status);
ffdkey(fptr, "DATASUM", &status);
/*
############################
# close file and quit #
############################
*/
errstatus: /* jump here on error */
ffclos(fptr, &status);
printf("ffclos status = %d\n", status);
printf("\nNormally, there should be 8 error messages on the stack\n");
printf("all regarding 'numerical overflows':\n");
ffgmsg(errmsg);
nmsg = 0;
while (errmsg[0])
{
printf(" %s\n", errmsg);
nmsg++;
ffgmsg(errmsg);
}
if (nmsg != 8)
printf("\nWARNING: Did not find the expected 8 error messages!\n");
ffgerr(status, errmsg);
printf("\nStatus = %d: %s\n", status, errmsg);
/* free the allocated memory */
for (ii = 0; ii < 21; ii++)
free(inskey[ii]);
for (ii = 0; ii < 10; ii++)
{
free(ttype[ii]);
free(tform[ii]);
free(tunit[ii]);
}
return(status);
}
| [
"[email protected]"
] | |
ee8adc4252d72141bc6f0adec445f56692dca1d8 | 4463a4482f44a007d37dc5ab9aac5a4d5bd37300 | /desktop/vsm.c | f6ecf46727316016a84c031c52d61df0b3cdaa26 | [] | no_license | gpertea/mgblast | e25cb219ac4c7fa123ceee4156be1e9c4f87997f | d06af0c2b3e72a8209f958d2b64510c83bf2a4a1 | refs/heads/master | 2021-01-22T05:01:00.918428 | 2017-02-10T21:45:26 | 2017-02-10T21:45:26 | 81,608,439 | 5 | 2 | null | null | null | null | UTF-8 | C | false | false | 71,484 | c | /* vsm.c
* ===========================================================================
*
* PUBLIC DOMAIN NOTICE
* National Center for Biotechnology Information (NCBI)
*
* This software/database is a "United States Government Work" under the
* terms of the United States Copyright Act. It was written as part of
* the author's official duties as a United States Government employee and
* thus cannot be copyrighted. This software/database is freely available
* to the public for use. The National Library of Medicine and the U.S.
* Government do not place any restriction on its use or reproduction.
* We would, however, appreciate having the NCBI and the author cited in
* any work or product based on this material
*
* Although all reasonable efforts have been taken to ensure the accuracy
* and reliability of the software and data, the NLM and the U.S.
* Government do not and cannot warrant the performance or results that
* may be obtained by using this software or data. The NLM and the U.S.
* Government disclaim all warranties, express or implied, including
* warranties of performance, merchantability or fitness for any particular
* purpose.
*
* ===========================================================================
*
* File Name: vsm.c
*
* Author: Jim Ostell
*
* Version Creation Date: 11-29-94
*
* $Revision: 6.21 $
*
* File Description:
*
* Modifications:
* --------------------------------------------------------------------------
* Date Name Description of modification
* ------- ---------- -----------------------------------------------------
*
*
* ==========================================================================
*/
#include <vsmpriv.h>
#include <objsub.h>
#include <objfdef.h>
#include <dlogutil.h>
#include <bspview.h>
#include <salpacc.h>
static VSMWinPtr NEAR VSMWinNew PROTO((VSeqMgrPtr vsmp));
static void NEAR VSMWinShow PROTO((VSMWinPtr vsmwp));
static void NEAR VSMWinDelete PROTO((VSMWinPtr vsmwp, Uint2 entityID, Uint2 itemID,
Uint2 itemtype));
static void NEAR VSMWinRefreshData PROTO((VSMWinPtr vsmwp, Uint2 entityID,
Uint2 itemID, Uint2 itemtype));
static void NEAR VSMPictSelect PROTO((VSMPictPtr vsmpp,
Uint2 entityID, Uint2 itemID, Uint2 itemtype, Boolean select));
static VSMWinPtr NEAR VSeqMgrGetWinForW PROTO((WindoW w));
static Boolean NEAR VSeqMgrCreateMainWindow PROTO((VSeqMgrPtr vsmp, Boolean program_window));
static void NEAR VSeqMgrPopulateMain PROTO((VSMWinPtr vsmwp));
#define VSM_PICT_UP_BUTTON 65001
#define VSM_PICT_DOWN_BUTTON 65002
SegmenT VSMEntityDraw PROTO((ObjMgrDataPtr omdp, VSMPictPtr vsmpp, VSeqMgrPtr vsmp));
static OMUserDataPtr NEAR VSMAddPictureToEntity PROTO((VSMWinPtr vsmwp, Uint2 entityID, Int2 expand));
/*****************************************************************************
*
* VSeqMgrGenFunc()
* General function to call from ObjMgr
*
*****************************************************************************/
Int2 LIBCALLBACK VSeqMgrGenFunc PROTO((Pointer ompcp));
/*****************************************************************************
*
* VSeqMgrMsgFunc()
* function to call on each DeskTop window by the ObjMgr
*
*****************************************************************************/
Int2 LIBCALLBACK VSeqMgrMsgFunc PROTO((OMMsgStructPtr ommsp));
Int2 LIBCALLBACK VSMPictMsgFunc PROTO((OMMsgStructPtr ommsp));
/*****************************************************************************
*
* Public VSeqMgr Functions
*
*****************************************************************************/
/*****************************************************************************
*
* VSeqMgrInit(show)
* if (show) displays the window.
* OtherWise, just initializes.
*
*****************************************************************************/
Boolean LIBCALL VSeqMgrInit (Boolean show)
{
VSeqMgrPtr vsmp;
if (show)
{
return VSeqMgrShow();
}
vsmp = VSeqMgrGet();
if (vsmp == NULL) return FALSE;
return TRUE;
}
/*****************************************************************************
*
* VSeqMgrShow()
* display the VSeqMgr
* initializes if not already done
*
*****************************************************************************/
Boolean LIBCALL VSeqMgrShow(void)
{
VSeqMgrPtr vsmp;
VSMWinPtr tmp, next=NULL;
/***
Message(MSG_OK, "In VSeqMgrShow");
***/
vsmp = VSeqMgrGet();
for (tmp = vsmp->wins; tmp != NULL; tmp = tmp->next)
{
tmp->in_process = TRUE;
VSMWinRefreshData(tmp, 0,0,0);
VSMWinShow(tmp);
}
return TRUE;
}
/*****************************************************************************
*
* VSeqMgrDelete()
* removes the VSeqMgr from the screen
* keeps settings for the main window
*
*****************************************************************************/
Boolean LIBCALL VSeqMgrDelete(void)
{
VSeqMgrPtr vsmp;
VSMWinPtr tmp, next=NULL;
vsmp = VSeqMgrGet();
for (tmp = vsmp->wins; tmp != NULL; tmp = next)
{
next = tmp->next;
VSMWinDelete(tmp, 0,0,0);
}
return TRUE;
}
static char * VSeqMgrStr = "NCBIDT";
/*****************************************************************************
*
* Return the current VSeqMgr
* Initialize if not done already
*
*****************************************************************************/
VSeqMgrPtr LIBCALL VSeqMgrGet (void)
{
VSeqMgrPtr vsmp=NULL;
vsmp = (VSeqMgrPtr) GetAppProperty(VSeqMgrStr);
if (vsmp == NULL)
{ /*** have to initialize it **/
vsmp = (VSeqMgrPtr) MemNew (sizeof(VSeqMgr));
/*** initialize the functions **/
vsmp->omp = ObjMgrGet();
vsmp->appname = StringSave(VSeqMgrStr); /* used for the app file as well */
SetAppProperty (VSeqMgrStr, (void *) vsmp);
VSeqMgrCreateMainWindow(vsmp, FALSE);
}
return vsmp;
}
/*****************************************************************************
*
* Run VSeqMgr as the main program
* Initialize if not done already
*
*****************************************************************************/
void LIBCALL VSeqMgrRun (CharPtr title, CharPtr aboutinfo)
{
VSeqMgrPtr vsmp=NULL;
vsmp = (VSeqMgrPtr) GetAppProperty(VSeqMgrStr);
if (vsmp == NULL)
{ /*** have to initialize it **/
vsmp = (VSeqMgrPtr) MemNew (sizeof(VSeqMgr));
vsmp->aboutinfo = StringSave(aboutinfo);
vsmp->title = StringSave(title);
/*** initialize the functions **/
vsmp->omp = ObjMgrGet();
vsmp->appname = StringSave(VSeqMgrStr); /* used for the app file as well */
SetAppProperty (VSeqMgrStr, (void *) vsmp);
if (! VSeqMgrCreateMainWindow(vsmp, TRUE))
return;
}
VSeqMgrShow();
ProcessEvents();
return;
}
static void QuitVSeqMgr (WindoW w)
{
VSMWinPtr vsmwp;
vsmwp = VSeqMgrGetWinForW(w);
if (vsmwp->is_main_VSM)
VSeqMgrDelete();
else
VSMWinDelete(vsmwp,0,0,0);
return;
}
static void ResizeVSeqMgr (WindoW w)
{
VSMWinPtr vsmwp;
vsmwp = VSeqMgrGetWinForW(w);
/***
Message(MSG_OK, "In Resize");
***/
if (vsmwp != NULL)
{
if (vsmwp->shown && (! vsmwp->in_process))
{
vsmwp->in_process = TRUE;
VSMWinRefreshData(vsmwp, 0,0,0);
vsmwp->in_process = FALSE;
/**
VSMWinShow(vsmwp);
**/
}
}
return;
}
static void NEAR VSMWinShow (VSMWinPtr vsmwp)
{
if (vsmwp == NULL) return;
/***
Message(MSG_OK, "In VSMWinShow");
***/
if (! vsmwp->populated)
{
vsmwp->in_process = TRUE;
VSMWinRefreshData(vsmwp, 0,0,0);
}
vsmwp->in_process = FALSE;
if (! vsmwp->shown)
{
Show(vsmwp->w);
vsmwp->shown = TRUE;
Select(vsmwp->w);
}
return;
}
static void NEAR VSMWinRefreshData (VSMWinPtr vsmwp, Uint2 entityID,
Uint2 itemID, Uint2 itemtype)
{
if (vsmwp == NULL) return;
/**
Message(MSG_OK, "In refresh data");
**/
/* not on screen and not being prepared for screen */
if (! (vsmwp->shown || vsmwp->in_process))
return;
if (vsmwp->entityID == 0)
VSeqMgrPopulateMain(vsmwp);
else
Message(MSG_ERROR, "Got a non-main window in refresh");
return;
}
static void VSeqMgrOpenMenuProc (IteM i)
{
Int2 retval;
ObjMgrProcPtr ompp;
OMProcControl ompc;
ompp = (ObjMgrProcPtr) GetObjectExtra(i);
if (ompp == NULL || ompp->func == NULL)
return;
MemSet(&ompc, 0, sizeof(OMProcControl));
ompc.proc = ompp;
retval = (*(ompp->func)) (&ompc);
if (retval == OM_MSG_RET_ERROR)
ErrShow();
return;
}
static void VSeqMgrSaveMenuProc (IteM i)
{
Int2 retval;
ObjMgrProcPtr ompp;
OMProcControl ompc;
ompp = (ObjMgrProcPtr) GetObjectExtra(i);
if (ompp == NULL || ompp->func == NULL)
return;
MemSet(&ompc, 0, sizeof(OMProcControl));
ompc.do_not_reload_from_cache = TRUE;
if (! GatherDataForProc(&ompc, TRUE)) /* anything selected? */
{
ErrShow();
Message (MSG_ERROR, "Nothing selected");
return;
}
ompc.proc = ompp;
retval = (*(ompp->func)) (&ompc);
if (retval == OM_MSG_RET_ERROR)
ErrShow();
return;
}
/*
static Boolean ObjMgrProcMatch (ObjMgrProcPtr ompp, OMProcControlPtr ompcp, Boolean showerror)
{
ObjMgrTypePtr omtp1, omtp2;
ObjMgrPtr omp;
Boolean ok = FALSE;
Uint2 subtype=0;
Pointer ptr=NULL;
if ((ompp == NULL) || (ompcp == NULL))
return FALSE;
if (ompp->inputtype == 0)
return TRUE;
if (ompp->inputtype == ompcp->input_itemtype)
{
ok = TRUE;
ptr = ompcp->input_data;
}
else if (ompp->inputtype == ompcp->input_choicetype)
{
ok = TRUE;
ptr = ompcp->input_choice;
}
if (ok)
{
if (ompp->subinputtype != 0)
{
omp = ObjMgrGet();
omtp1 = ObjMgrTypeFind(omp, ompp->inputtype, NULL, NULL);
if (omtp1 != NULL)
subtype = (*(omtp1->subtypefunc)) (ptr);
if (subtype != ompp->subinputtype)
{
if (showerror)
ErrPostEx(SEV_ERROR,0,0,"Trying to put subtype %d into function taking subtype %d",
(int)subtype, (int)(ompp->subinputtype));
return FALSE;
}
}
}
if (! ok)
{
if (showerror)
{
omp = ObjMgrGet();
omtp1 = ObjMgrTypeFind(omp, ompp->inputtype, NULL, NULL);
if (omtp1 == NULL)
{
ErrPostEx(SEV_ERROR,0,0,"Input type for function not registered");
return FALSE;
}
omtp2 = ObjMgrTypeFind(omp, ompcp->input_itemtype, NULL, NULL);
if (omtp2 == NULL)
{
ErrPostEx(SEV_ERROR,0,0,"Selected data type not registered");
return FALSE;
}
ErrPostEx(SEV_ERROR,0,0,"Trying to put a %s into function taking a %s",
omtp2->label, omtp1->label);
}
return FALSE;
}
return TRUE;
}
*/
static void ShowVSMProc (IteM i)
{
VSeqMgrShow();
return;
}
typedef struct sbstruc {
CharPtr name;
MenU menu;
} Sbstruc, PNTR SbstrucPtr;
static void VSeqMgrStdMenuProc (IteM i)
{
Int2 retval;
ObjMgrProcPtr ompp;
OMProcControl ompc;
ompp = (ObjMgrProcPtr) GetObjectExtra(i);
if (ompp == NULL || ompp->func == NULL)
return;
MemSet(&ompc, 0, sizeof(OMProcControl));
ompc.do_not_reload_from_cache = TRUE;
GatherDataForProc(&ompc, TRUE);
ompc.proc = ompp;
retval = (*(ompp->func)) (&ompc);
if (retval == OM_MSG_RET_ERROR)
ErrShow();
/*
if (! GatherDataForProc(&ompc, TRUE))
{
ErrShow();
return;
}
if (ObjMgrProcMatch(ompp, &ompc, TRUE))
{
ompc.proc = ompp;
retval = (*(ompp->func)) (&ompc);
if (retval == OM_MSG_RET_ERROR)
ErrShow();
}
else
ErrShow();
*/
return;
}
/*****************************************************************************
*
* VSMAddToMenu(MenU m, Int2 menutype)
* Adds a VSM style submenu to Menu
* All included procs must have already been registered with the
* objmgr.
*
*****************************************************************************/
Boolean LIBCALL VSMAddToMenu (MenU m, Int2 menutype)
{
MenU s, x;
ObjMgrProcPtr ompp;
ObjMgrPtr omp;
VSeqMgrPtr vsmp;
Int2 ctr, proctype;
static Int2 proctypes [3] = {
0,
OMPROC_OPEN,
OMPROC_SAVE};
static CharPtr menuname [3] = {
"NCBI DeskTop",
"Open",
"Save As"};
ValNodePtr submenulist = NULL, vnp;
SbstrucPtr sbp;
IteM i;
if (m == NULL) return FALSE;
if (menutype == VSM_DESKTOP)
{
CommandItem(m, menuname[menutype], ShowVSMProc);
return TRUE;
}
else if (menutype != VSM_OPEN_MENU && menutype != VSM_SAVE_MENU)
{
return FALSE;
}
proctype = proctypes[menutype];
vsmp = VSeqMgrGet();
omp = vsmp->omp;
s = SubMenu (m, menuname[menutype]);
ompp = NULL;
ctr = 0;
while ((ompp = ObjMgrProcFindNext(omp, proctype, 0,0, ompp)) != NULL)
{
x = NULL;
if (! StringHasNoText (ompp->submenu)) {
vnp = submenulist;
while (vnp != NULL && x == NULL) {
sbp = (SbstrucPtr) vnp->data.ptrvalue;
if (sbp != NULL) {
if (StringICmp (ompp->submenu, sbp->name) == 0) {
x = sbp->menu;
}
}
vnp = vnp->next;
}
if (x == NULL) {
sbp = (SbstrucPtr) MemNew (sizeof (Sbstruc));
if (sbp != NULL) {
sbp->name = ompp->submenu;
sbp->menu = SubMenu (s, sbp->name);
x = sbp->menu;
ValNodeAddPointer (&submenulist, 0, (VoidPtr) sbp);
}
}
}
if (x == NULL) {
x = s;
}
if (menutype == VSM_OPEN_MENU)
{
i = CommandItem(x, ompp->proclabel, VSeqMgrOpenMenuProc);
}
else if (menutype == VSM_SAVE_MENU)
{
i = CommandItem(x, ompp->proclabel, VSeqMgrSaveMenuProc);
}
SetObjectExtra(i, (VoidPtr)ompp, NULL);
ctr++;
vsmp->procmenu[proctype][ctr] = ompp->procid;
}
return TRUE;
}
/*****************************************************************************
*
* VSMAddMenu(WindoW w, Int2 menutype)
* Adds a VSM style menu to Window
* All included procs must have already been registered with the
* objmgr.
* If no procs of this type are registered, does not add to window
*
*****************************************************************************/
Boolean LIBCALL VSMAddMenu (WindoW w, Int2 menutype)
{
MenU m, sub, sub2, x;
ObjMgrProcPtr ompp;
ObjMgrPtr omp;
ObjMgrTypePtr omtp;
VSeqMgrPtr vsmp;
Int2 ctr, proctype;
FeatDispGroupPtr fdgp;
FeatDefPtr fdp;
Uint1 key;
CharPtr label;
static Int2 proctypes [5] = {
0,
OMPROC_FILTER ,
OMPROC_ANALYZE ,
OMPROC_VIEW ,
OMPROC_EDIT } ;
static CharPtr menuname [5] = {
NULL,
"Filter",
"Analysis",
"View",
"Editor" };
IteM i;
ValNodePtr submenulist = NULL, vnp;
SbstrucPtr sbp;
Uint2 subtype;
#ifndef WIN_MAC
if (w == NULL) return FALSE;
#endif
switch (menutype)
{
case VSM_FILTER_MENU:
case VSM_ANALYZE_MENU:
case VSM_VIEW_MENU:
proctype = proctypes[menutype];
vsmp = VSeqMgrGet();
omp = vsmp->omp;
ompp = ObjMgrProcFindNext(omp, proctype, 0,0, NULL);
if (ompp == NULL) /* none registered */
return FALSE;
m = PulldownMenu(w, menuname[menutype]);
ctr = 0;
do
{
x = NULL;
if (! StringHasNoText (ompp->submenu)) {
vnp = submenulist;
while (vnp != NULL && x == NULL) {
sbp = (SbstrucPtr) vnp->data.ptrvalue;
if (sbp != NULL) {
if (StringICmp (ompp->submenu, sbp->name) == 0) {
x = sbp->menu;
}
}
vnp = vnp->next;
}
if (x == NULL) {
sbp = (SbstrucPtr) MemNew (sizeof (Sbstruc));
if (sbp != NULL) {
sbp->name = ompp->submenu;
sbp->menu = SubMenu (m, sbp->name);
x = sbp->menu;
ValNodeAddPointer (&submenulist, 0, (VoidPtr) sbp);
}
}
}
if (x == NULL) {
x = m;
}
i = CommandItem(x, ompp->proclabel, VSeqMgrStdMenuProc);
SetObjectExtra(i, (VoidPtr)ompp, NULL);
ctr++;
}
while ((ompp = ObjMgrProcFindNext(omp, proctype, 0,0, ompp)) != NULL);
ValNodeFree (submenulist);
return TRUE;
case VSM_EDIT_MENU:
proctype = proctypes[menutype];
vsmp = VSeqMgrGet();
omp = vsmp->omp;
ompp = ObjMgrProcFindNext(omp, proctype, 0,0, NULL);
if (ompp == NULL) /* none registered */
return FALSE;
m = PulldownMenu(w, menuname[menutype]);
/* code is below this switch statement */
break;
default:
return FALSE;
}
omtp = NULL;
ctr = 0;
while ((omtp = ObjMgrTypeFindNext(omp, omtp)) != NULL) {
ompp = ObjMgrProcFindNext(omp, proctype, omtp->datatype, 0, NULL);
if (ompp != NULL) {
if (omtp->datatype == OBJ_SEQFEAT) {
sub = SubMenu (m, omtp->label);
fdgp = NULL;
while ((fdgp = DispGroupFindNext (fdgp, &key, &label)) != NULL) {
if (fdgp->groupkey != 0) {
sub2 = SubMenu (sub, fdgp->groupname);
fdp = NULL;
label = NULL;
while ((fdp = FeatDefFindNext (fdp, &key, &label, fdgp->groupkey, FALSE)) != NULL) {
if (key != FEATDEF_BAD) {
ompp = NULL;
while ((ompp = ObjMgrProcFindNext(omp, proctype,
omtp->datatype, 0, ompp)) != NULL) {
if (ompp->subinputtype == fdp->featdef_key) {
i = CommandItem(sub2, ompp->proclabel, VSeqMgrStdMenuProc);
SetObjectExtra(i, (VoidPtr)ompp, NULL);
ctr++;
}
}
}
}
}
}
sub2 = SubMenu (sub, "Remaining Features");
fdp = NULL;
while ((fdp = FeatDefFindNext (fdp, &key, &label, 0, FALSE)) != NULL) {
if (key != FEATDEF_BAD) {
ompp = NULL;
while ((ompp = ObjMgrProcFindNext (omp, proctype,
omtp->datatype, 0, ompp)) != NULL) {
subtype = ompp->subinputtype;
if (subtype == fdp->featdef_key &&
subtype != FEATDEF_PUB &&
subtype != FEATDEF_Imp_CDS &&
subtype != FEATDEF_misc_RNA &&
subtype != FEATDEF_precursor_RNA &&
subtype != FEATDEF_mat_peptide &&
subtype != FEATDEF_sig_peptide &&
subtype != FEATDEF_transit_peptide &&
subtype != FEATDEF_source &&
subtype != FEATDEF_virion &&
subtype != FEATDEF_mutation &&
subtype != FEATDEF_allele &&
subtype != FEATDEF_site_ref &&
subtype != FEATDEF_gap) {
i = CommandItem (sub2, ompp->proclabel, VSeqMgrStdMenuProc);
SetObjectExtra(i, (VoidPtr)ompp, NULL);
ctr++;
}
}
}
}
} else {
sub = SubMenu (m, omtp->label);
do
{
i = CommandItem(sub, ompp->proclabel, VSeqMgrStdMenuProc);
SetObjectExtra(i, (VoidPtr)ompp, NULL);
ctr++;
}
while ((ompp = ObjMgrProcFindNext(omp, proctype,
omtp->datatype, 0, ompp)) != NULL);
}
}
}
return TRUE;
}
static void VSeqMgrQuitProc (IteM i)
{
VSeqMgrDelete();
return;
}
static void VSeqMgrEditProc (IteM i)
{
Message(MSG_OK, "Edit");
return;
}
static void VSeqMgrCutProc (IteM i)
{
OMProcControl ompc;
MemSet(&ompc, 0, sizeof(OMProcControl));
ompc.do_not_reload_from_cache = TRUE;
if (! DetachDataForProc(&ompc, TRUE)) /* anything selected? */
{
ErrShow();
return;
}
if (! ompc.whole_entity) /* just a part gone, so need an update */
ObjMgrSendMsg(OM_MSG_DEL, ompc.input_entityID, ompc.input_itemID, ompc.input_itemtype);
if (! ObjMgrAddToClipBoard (0, ompc.input_data))
ErrShow();
return;
}
static void VSeqMgrCopyProc (IteM i)
{
OMProcControl ompc;
MemSet(&ompc, 0, sizeof(OMProcControl));
ompc.do_not_reload_from_cache = TRUE;
if (! CopyDataForProc(&ompc, TRUE)) /* anything selected? */
{
ErrShow();
return;
}
if (ompc.output_data == NULL)
{
ErrShow();
return;
}
if (! ObjMgrAddToClipBoard (0, ompc.output_data))
ErrShow();
return;
}
static void VSeqMgrPasteProc (IteM i)
{
OMProcControl ompc;
ObjMgrDataPtr omdp;
ObjMgrTypePtr omtp;
SelStructPtr ssp;
ObjMgrPtr omp;
Uint2 type;
Pointer ptr;
omdp = ObjMgrGetClipBoard();
if (omdp == NULL)
{
Message(MSG_ERROR, "No data in clipboard");
return;
}
MemSet(&ompc, 0, sizeof(OMProcControl));
ompc.input_data = omdp->dataptr;
ompc.input_entityID = omdp->EntityID;
ompc.input_choice = omdp->choice;
ompc.input_itemtype = omdp->datatype;
ompc.input_itemID = 1;
ompc.input_choicetype = omdp->choicetype;
ompc.whole_entity = TRUE;
ompc.do_not_reload_from_cache = TRUE;
if (! CopyDataForProc(&ompc, FALSE)) /* just do the copy */
{
ErrShow();
return;
}
if (ompc.output_data == NULL)
{
ErrShow();
return;
}
ompc.input_data = NULL;
ompc.input_entityID = 0;
ompc.input_choice = NULL;
ompc.input_itemtype = 0;
ompc.input_choicetype = 0;
ompc.whole_entity = FALSE;
ompc.do_not_reload_from_cache = TRUE;
ssp = ObjMgrGetSelected();
if (ssp == NULL) /* nothing selected, paste into main window */
{
ObjMgrRegister(ompc.output_itemtype, ompc.output_data);
return;
}
if (! AttachDataForProc(&ompc, TRUE))
{
ErrShow();
if (ompc.output_choice != NULL)
{
ptr = ompc.output_choice;
type = ompc.output_choicetype;
}
else
{
ptr = ompc.output_data;
type = ompc.output_itemtype;
}
omp = ObjMgrGet();
omtp = ObjMgrTypeFind(omp, type,NULL,NULL);
if (omtp != NULL)
(*(omtp->freefunc))(ptr);
}
else
ObjMgrSendMsg(OM_MSG_UPDATE, ompc.input_entityID, ompc.input_itemID, ompc.input_itemtype);
return;
}
static void VSeqMgrMoveProc (IteM i)
{
OMProcControl ompc;
ObjMgrDataPtr omdp;
ObjMgrTypePtr omtp;
SelStructPtr ssp;
ObjMgrPtr omp;
Uint2 type;
Pointer ptr;
omdp = ObjMgrGetClipBoard();
if (omdp == NULL)
{
Message(MSG_ERROR, "No data in clipboard");
return;
}
MemSet(&ompc, 0, sizeof(OMProcControl));
ompc.output_data = omdp->dataptr;
ompc.output_entityID = omdp->EntityID;
ompc.output_choice = omdp->choice;
ompc.output_itemtype = omdp->datatype;
ompc.output_choicetype = omdp->choicetype;
ompc.whole_entity = TRUE;
ompc.do_not_reload_from_cache = TRUE;
ssp = ObjMgrGetSelected();
if (ssp == NULL) /* nothing selected, paste into main window */
{
ObjMgrRegister(ompc.output_itemtype, ompc.output_data);
return;
}
if (! AttachDataForProc(&ompc, TRUE))
{
ErrShow();
if (ompc.output_choice != NULL)
{
ptr = ompc.output_choice;
type = ompc.output_choicetype;
}
else
{
ptr = ompc.output_data;
type = ompc.output_itemtype;
}
omp = ObjMgrGet();
omtp = ObjMgrTypeFind(omp, type,NULL,NULL);
if (omtp != NULL)
(*(omtp->freefunc))(ptr);
}
else
ObjMgrSendMsg(OM_MSG_UPDATE, ompc.input_entityID, ompc.input_itemID, ompc.input_itemtype);
return;
}
typedef struct warnifalignmentdata {
Boolean found;
SeqEntryPtr lookingfor;
} WarnIfAlignmentData, PNTR WarnIfAlignmentPtr;
static Boolean IsSeqEntryInAlignment (SeqAlignPtr salp, SeqEntryPtr sep)
{
BioseqPtr bsp;
BioseqSetPtr bssp;
SeqIdPtr sip;
Boolean found = FALSE;
SeqEntryPtr this_sep;
if (IS_Bioseq (sep)) {
bsp = (BioseqPtr) sep->data.ptrvalue;
for (sip = bsp->id; sip != NULL && ! found; sip = sip->next) {
found = SeqAlignFindSeqId (salp, sip);
}
} else if (IS_Bioseq_set (sep)) {
bssp = (BioseqSetPtr) sep->data.ptrvalue;
for (this_sep = bssp->seq_set;
this_sep != NULL && !found;
this_sep = this_sep->next) {
found = IsSeqEntryInAlignment (salp, this_sep);
}
}
return found;
}
static void FindAlignmentCallback (SeqAnnotPtr sap, Pointer userdata)
{
WarnIfAlignmentPtr wiap;
SeqAlignPtr salp;
if (sap == NULL || sap->type != 2 || userdata == NULL) {
return;
}
wiap = (WarnIfAlignmentPtr) userdata;
if (wiap->found) return;
salp = (SeqAlignPtr) sap->data;
if (salp == NULL) return;
wiap->found = IsSeqEntryInAlignment (salp, wiap->lookingfor);
}
static void WarnIfAlignment (Uint2 type, Pointer ptr, Uint2 input_entityID)
{
SeqEntryPtr sep;
SeqEntryPtr topsep;
WarnIfAlignmentData wiad;
if (type == 1) {
sep = (SeqEntryPtr) ptr;
} else {
return;
}
topsep = GetTopSeqEntryForEntityID (input_entityID);
wiad.found = FALSE;
wiad.lookingfor = sep;
VisitAnnotsInSep (topsep, &wiad, FindAlignmentCallback);
if (wiad.found) {
Message (MSG_OK, "Warning - this sequence is part of an alignment.");
}
}
static void VSeqMgrDeleteProc (IteM i)
{
OMProcControl ompc;
ObjMgrTypePtr omtp;
ObjMgrPtr omp;
Uint2 type;
Pointer ptr;
MemSet(&ompc, 0, sizeof(OMProcControl));
ompc.do_not_reload_from_cache = TRUE;
if (! DetachDataForProc(&ompc, TRUE)) /* anything selected? */
{
ErrShow();
return;
}
if (ompc.input_choicetype)
{
type = ompc.input_choicetype;
ptr = ompc.input_choice;
}
else
{
type = ompc.input_itemtype;
ptr = ompc.input_data;
}
WarnIfAlignment (type, ptr, ompc.input_entityID);
omp = ObjMgrGet();
omtp = ObjMgrTypeFind(omp, type, NULL, NULL);
if (omtp == NULL)
{
Message(MSG_ERROR, "Delete: type [%d] not registered", (int)type);
return;
}
(*(omtp->freefunc))(ptr);
if (! ompc.whole_entity) /* just a part gone, so need an update */
ObjMgrSendMsg(OM_MSG_DEL, ompc.input_entityID, ompc.input_itemID, ompc.input_itemtype);
return;
}
static void VSMDragAndDrop(VSMWinPtr vsmwp, Uint2 entityID, Uint2 itemID, Uint2 itemtype)
{
OMProcControl ompc;
MemSet(&ompc, 0, sizeof(OMProcControl));
ompc.input_entityID = vsmwp->entityID1;
ompc.input_itemID = vsmwp->itemID1;
ompc.input_itemtype = vsmwp->itemtype1;
ompc.do_not_reload_from_cache = TRUE;
if (! DetachDataForProc(&ompc, FALSE))
{
ErrShow();
return;
}
if (ompc.input_choicetype)
{
WarnIfAlignment (ompc.input_choicetype, ompc.input_choice, ompc.input_entityID);
}
else
{
WarnIfAlignment (ompc.input_itemtype, ompc.input_data, ompc.input_entityID);
}
if (! ompc.whole_entity) /* just a part gone, so need an update */
ObjMgrSendMsg(OM_MSG_DEL, ompc.input_entityID, ompc.input_itemID, ompc.input_itemtype);
if (entityID == 0) /* going into desktop */
{
ObjMgrSendMsg(OM_MSG_UPDATE, ompc.input_entityID, ompc.input_itemID, ompc.input_itemtype);
ObjMgrRegister(ompc.input_itemtype, ompc.input_data);
return;
}
ompc.output_entityID = ompc.input_entityID;
ompc.output_itemID = ompc.input_itemID;
ompc.output_itemtype = ompc.input_itemtype;
ompc.output_choice = ompc.input_choice;
ompc.output_data = ompc.input_data;
ompc.output_choicetype = ompc.input_choicetype;
ompc.whole_entity = FALSE;
ompc.input_entityID = entityID;
ompc.input_itemID = itemID;
ompc.input_itemtype = itemtype;
ompc.input_choicetype = 0;
ompc.input_choice = NULL;
ompc.input_data = NULL;
ompc.do_not_reload_from_cache = TRUE;
if (! AttachDataForProc(&ompc, FALSE))
{
ErrShow(); /* put in desktop */
ObjMgrRegister(ompc.output_itemtype, ompc.output_data);
}
else
ObjMgrSendMsg(OM_MSG_UPDATE, ompc.input_entityID, ompc.input_itemID, ompc.input_itemtype);
return;
}
static void VSeqMgrFontProc (IteM i)
{
VSeqMgrPtr vsmp;
Nlm_FontSpec font;
FonT f;
Char fontbuf[80];
vsmp = VSeqMgrGet();
GetFontSpec(vsmp->font, &font);
if (ChooseFont(&font, CFF_READ_FSP, NULL))
{
/***
f = GetPermanentFont(&font);
***/
f = CreateFont(&font);
vsmp->font = f;
SelectFont(f);
vsmp->lineheight = LineHeight();
vsmp->leading = Leading();
vsmp->charw = MaxCharWidth();
vsmp->update_all = TRUE;
VSeqMgrShow();
vsmp->update_all = FALSE;
FontSpecToStr(&font, fontbuf, 80);
SetAppParam(vsmp->appname, "DeskTop", "FONT", fontbuf);
}
return;
}
static void VSeqMgrShowCacheProc (IteM i)
{
VSeqMgrPtr vsmp;
vsmp = VSeqMgrGet();
if (vsmp->show_cached)
vsmp->show_cached = FALSE;
else
vsmp->show_cached = TRUE;
SetStatus(i, vsmp->show_cached);
vsmp->update_all = TRUE;
VSeqMgrShow();
vsmp->update_all = FALSE;
return;
}
static void VSeqMgrShowClipboardProc (IteM i)
{
VSeqMgrPtr vsmp;
vsmp = VSeqMgrGet();
if (vsmp->show_clipboard)
vsmp->show_clipboard = FALSE;
else
vsmp->show_clipboard = TRUE;
SetStatus(i, vsmp->show_clipboard);
vsmp->update_all = TRUE;
VSeqMgrShow();
vsmp->update_all = FALSE;
return;
}
static void VSMMarquee( VSMWinPtr vsmwp )
{
RecT dr;
WidePen(4);
InvertMode();
Dotted();
SectRect(&(vsmwp->r), &(vsmwp->rv), &dr);
FrameRect(&dr);
return;
}
static void VSeqMgrClickProc (VieweR v, SegmenT s, PoinT p)
{
VSMWinPtr vsmwp;
SegmenT sp, top, prev, next;
Uint2 segID, primID, primCt;
BoxInfo box;
PntInfo pi;
PoinT tl, br;
vsmwp = (VSMWinPtr)GetViewerData(v);
if (vsmwp == NULL)
{
Message(MSG_ERROR, "vsmwp was NULL in ClickProc");
return;
}
vsmwp->dblclick = dblClick;
vsmwp->shftkey = shftKey;
vsmwp->dragged = FALSE;
if (dblClick)
{
if (vsmwp->marquee)
{
VSMMarquee(vsmwp);
vsmwp->marquee = FALSE;
}
return;
}
sp = FindSegment(v, p, &segID, &primID, &primCt);
if (sp == NULL)
{
if (vsmwp->marquee)
{
VSMMarquee(vsmwp);
vsmwp->marquee = FALSE;
}
return;
}
SegmentBox(sp, &box);
pi.x = box.left;
pi.y = box.top;
MapWorldToViewer(v, pi, &tl);
pi.x = box.right;
pi.y = box.bottom;
MapWorldToViewer(v, pi, &br);
LoadRect(&(vsmwp->r), tl.x, tl.y, br.x, br.y);
LoadPt (&(vsmwp->lastpnt), p.x, p.y);
vsmwp->marquee = TRUE;
VSMMarquee(vsmwp);
vsmwp->itemtype1 = segID;
vsmwp->itemID1 = primID;
top = sp;
prev = sp;
while ((next = ParentSegment(top)) != NULL)
{
prev = top;
top = next;
}
vsmwp->entityID1 = (Uint2)SegmentID(prev);
return;
}
static void VSeqMgrReleaseProc (VieweR v, SegmenT s, PoinT p)
{
VSMWinPtr vsmwp;
SegmenT sp, top, next, prev;
Uint2 segID, primID, primCt, entityID=0, itemtype = 0, itemID = 0;
Uint1 highlight = PLAIN_SEGMENT;
Int2 expand = 0;
Boolean do_drag = FALSE;
SeqViewProcsPtr svpp;
Int2 handled;
vsmwp = (VSMWinPtr)GetViewerData(v);
if (vsmwp == NULL)
{
Message(MSG_ERROR, "vsmwp was NULL in ReleaseProc");
return;
}
if (vsmwp->marquee)
{
VSMMarquee(vsmwp);
vsmwp->marquee = FALSE;
}
sp = FindSegment(v, p, &segID, &primID, &primCt);
if (sp == NULL)
{
if (! vsmwp->dragged)
ObjMgrDeSelectAll();
else
do_drag = TRUE;
}
else
{
itemtype = segID;
itemID = primID;
top = sp;
prev = sp;
while ((next = ParentSegment(top)) != NULL)
{
prev = top;
top = next;
}
entityID = (Uint2)SegmentID(prev);
/***
Message(MSG_OK, "Calling ObjMgrSelect(%ld, %ld, %ld)",
(long)entityID, (long)itemID, (long)itemtype);
***/
if (vsmwp->dblclick) {
svpp = (SeqViewProcsPtr) GetAppProperty ("SeqDisplayForm");
if (svpp != NULL) {
if (svpp->launchEditors) {
WatchCursor ();
Update ();
handled = GatherProcLaunch (OMPROC_EDIT, FALSE, entityID, itemID,
itemtype, 0, 0, itemtype, 0);
ArrowCursor ();
Update ();
if (handled == OM_MSG_RET_DONE || handled == OM_MSG_RET_NOPROC) {
return;
}
}
}
return;
} else if ((! vsmwp->dragged) ||
((entityID == vsmwp->entityID1) &&
(itemID == vsmwp->itemID1) &&
(itemtype == vsmwp->itemtype1)))
{
if (itemID == VSM_PICT_UP_BUTTON)
expand = 1;
else if (itemID == VSM_PICT_DOWN_BUTTON)
expand = -1;
if (! expand) {
if (vsmwp->shftkey) {
ObjMgrAlsoSelect(entityID, itemID, itemtype,0,NULL);
} else {
ObjMgrSelect(entityID, itemID, itemtype,0,NULL);
}
}
else
{
WatchCursor();
VSMAddPictureToEntity(vsmwp, entityID, expand);
VSMWinRefreshData(vsmwp, entityID, 0, 0);
ArrowCursor();
}
return;
}
else
do_drag = TRUE;
}
if (do_drag)
VSMDragAndDrop(vsmwp, entityID, itemID, itemtype);
return;
}
static void VSeqMgrDragProc (VieweR v, SegmenT s, PoinT p)
{
VSMWinPtr vsmwp;
vsmwp = (VSMWinPtr)GetViewerData(v);
if (vsmwp == NULL)
{
Message(MSG_ERROR, "vsmwp was NULL in DragProc");
return;
}
if (vsmwp->marquee)
{
vsmwp->dragged = TRUE;
VSMMarquee(vsmwp);
OffsetRect(&(vsmwp->r), p.x - vsmwp->lastpnt.x, p.y - vsmwp->lastpnt.y);
VSMMarquee(vsmwp);
LoadPt(&(vsmwp->lastpnt), p.x, p.y);
}
return;
}
static void VSMCenterLine (Nlm_RectPtr rptr, Nlm_CharPtr text, Nlm_FonT fnt)
{
if (fnt != NULL) {
Nlm_SelectFont (fnt);
}
rptr->bottom = rptr->top + Nlm_LineHeight ();
Nlm_DrawString (rptr, text, 'c', FALSE);
rptr->top = rptr->bottom;
}
static void VSMDrawAbout (Nlm_PaneL p)
{
Nlm_RecT r;
VSeqMgrPtr vsmp;
CharPtr ptr, tmp;
Char last = 'x';
FonT f1, f2;
Int2 bottom;
#ifdef WIN_MAC
f1 = ParseFont("Monaco,12");
f2 = ParseFont("Monaco,9");
#else
#ifdef WIN_MOTIF
f1 = ParseFont("Times,12");
f2 = ParseFont("Times,9");
#else
f1 = ParseFont("Times New Roman,12");
f2 = ParseFont("Times New Roman,9");
#endif
#endif
vsmp = VSeqMgrGet();
Nlm_ObjectRect (p, &r);
Nlm_InsetRect (&r, 4, 4);
bottom = r.bottom;
Nlm_Blue ();
VSMCenterLine (&r, "The NCBI DeskTop v1.0", f1);
VSMCenterLine (&r, "by James M. Ostell", f2);
VSMCenterLine (&r, "National Center for Biotechnology Information", f2);
VSMCenterLine (&r, "National Institutes of Health, Bethesda, MD USA", f2);
VSMCenterLine (&r, "(301) 496-2475 [email protected]", f2);
Nlm_Red();
SelectFont(f2);
r.top += LineHeight();
if (vsmp->title != NULL)
VSMCenterLine(&r, vsmp->title, f1);
if (vsmp->aboutinfo != NULL)
{
ptr = vsmp->aboutinfo;
tmp = ptr;
while ((*ptr != '\0') && (r.top <= bottom))
{
while ((*tmp != '\0') && (*tmp != '~'))
tmp++;
last = *tmp;
*tmp = '\0';
VSMCenterLine(&r, ptr, f2);
*tmp = last;
tmp++;
ptr = tmp;
}
}
return;
}
static void QuitVSMAbout (WindoW w)
{
Remove(w);
return;
}
static void VSMAboutProc (IteM i)
{
WindoW w;
PaneL p;
w = FixedWindow (-50, -33, -10, -10, "About NCBI DeskTop", QuitVSMAbout);
p = SimplePanel (w, 28 * stdCharWidth, 12 * stdLineHeight, VSMDrawAbout);
Show (w);
return;
}
static void QuitVSM (WindoW w)
{
QuitProgram();
return;
}
static void VSMQuitProc (IteM i)
{
QuitProgram();
return;
}
static void VSMSetUpMenus (WindoW w, Boolean progwindow)
{
MenU m;
if (progwindow)
{
#ifdef WIN_MAC
m = AppleMenu (NULL);
CommandItem (m, "About...", VSMAboutProc);
SeparatorItem (m);
DeskAccGroup (m);
#endif
m = PulldownMenu (w, "File");
#ifndef WIN_MAC
CommandItem (m, "About...", VSMAboutProc);
SeparatorItem (m);
#endif
}
else
{
m = PulldownMenu (w, "File");
}
VSMAddToMenu(m, VSM_OPEN_MENU);
VSMAddToMenu(m, VSM_SAVE_MENU);
if (progwindow)
CommandItem(m, "Quit/Q", VSMQuitProc);
else
CommandItem(m, "Quit/Q", VSeqMgrQuitProc);
m = PulldownMenu (w, "Edit");
CommandItem(m, "Edit/E", VSeqMgrEditProc);
CommandItem(m, "Cut/T", VSeqMgrCutProc);
CommandItem(m, "Copy/C", VSeqMgrCopyProc);
CommandItem(m, "Paste/P", VSeqMgrPasteProc);
CommandItem(m, "Move/M", VSeqMgrMoveProc);
CommandItem(m, "Delete/D", VSeqMgrDeleteProc);
VSMAddMenu(w, VSM_FILTER_MENU);
VSMAddMenu(w, VSM_VIEW_MENU);
VSMAddMenu(w, VSM_ANALYZE_MENU);
VSMAddMenu(w, VSM_EDIT_MENU);
m = PulldownMenu(w, "Options");
CommandItem(m, "Select Font", VSeqMgrFontProc);
StatusItem(m, "Show cached", VSeqMgrShowCacheProc);
StatusItem(m, "Show clipboard", VSeqMgrShowClipboardProc);
return;
}
/*****************************************************************************
*
* VSeqMgrCreateMainWindow()
*
*****************************************************************************/
typedef struct vsmform {
FORM_MESSAGE_BLOCK
} VSMForm, PNTR VSMFormPtr;
static void VSMFormMessage (ForM f, Int2 mssg)
{
VSMFormPtr vfp;
vfp = (VSMFormPtr) GetObjectExtra (f);
if (vfp != NULL) {
switch (mssg) {
case VIB_MSG_CLOSE :
QuitVSeqMgr ((WindoW) f);
break;
default :
if (vfp->appmessage != NULL) {
vfp->appmessage (f, mssg);
}
break;
}
}
}
static Boolean NEAR VSeqMgrCreateMainWindow(VSeqMgrPtr vsmp, Boolean progwindow)
{
VSMWinPtr vsmwp;
OMUserDataPtr omudp;
WindoW w;
VieweR v;
RecT rw, rv;
FonT f;
Char fontbuf[80];
ObjMgrPtr omp;
static CharPtr dttitle = "NCBI DeskTop";
CharPtr title;
VSMFormPtr vfp;
Int2 pixheight, pixwidth;
StdEditorProcsPtr sepp;
TextViewProcsPtr tvpp;
ProcessUpdatesFirst(FALSE);
WatchCursor();
if (vsmp->title != NULL)
title = vsmp->title;
else
title = dttitle;
w = NULL;
if (progwindow)
{
WatchCursor ();
ErrSetFatalLevel (SEV_MAX);
if (! SeqEntryLoad())
{
Message(MSG_ERROR, "SeqEntryLoadFailed");
ErrShow();
ArrowCursor();
return FALSE;
}
if (! SubmitAsnLoad())
{
Message(MSG_ERROR, "SubmitAsnLoadLoadFailed");
ErrShow();
ArrowCursor();
return FALSE;
}
/* initialize File I/O procs for VSM (vsmfile.h) */
/* could also add to your menu with VSMAddToMenu() (vsm.h) */
VSMFileInit();
#ifdef WIN_MAC
VSMSetUpMenus (NULL, progwindow);
#endif
w = DocumentWindow (-50, -33, -10, -10, title, QuitVSM, ResizeVSeqMgr);
#ifndef WIN_MAC
VSMSetUpMenus (w, progwindow);
#endif
}
else
{
w = DocumentWindow (-50, -33, -10, -10, title, QuitVSeqMgr, ResizeVSeqMgr);
VSMSetUpMenus (w, progwindow);
}
pixwidth = 300;
pixheight = 300;
if (w != NULL) {
vfp = (VSMFormPtr) MemNew (sizeof (VSMForm));
if (vfp != NULL) {
SetObjectExtra (w, vfp, StdCleanupFormProc);
vfp->form = (ForM) w;
vfp->formmessage = VSMFormMessage;
sepp = (StdEditorProcsPtr) GetAppProperty ("StdEditorForm");
if (sepp != NULL) {
SetActivate (w, sepp->activateForm);
vfp->appmessage = sepp->handleMessages;
}
}
}
omp = vsmp->omp;
tvpp = (TextViewProcsPtr) GetAppProperty ("TextDisplayForm");
if (tvpp != NULL) {
pixwidth = MAX (pixwidth, tvpp->minPixelWidth);
pixheight = MAX (pixheight, tvpp->minPixelHeight);
}
v = CreateViewer(w, pixwidth, pixheight, TRUE, TRUE);
RealizeWindow(w);
ObjectRect(w, &rw); /* calculate realation between window and viewer */
ObjectRect(v, &rv);
vsmp->xoff = rv.left;
vsmp->yoff = rv.top;
vsmp->x = (rw.right - rw.left + 1) - (rv.right - rv.left + 1) - rv.left
- vScrollBarWidth;
vsmp->y = (rw.bottom - rw.top + 1) - (rv.bottom - rv.top + 1) - rv.top
- hScrollBarHeight;
GetAppParam(vsmp->appname, "DeskTop", "FONT", "Times,10", fontbuf, 80);
f = ParseFont(fontbuf);
SetWindowExtra(w, (Pointer)v, NULL);
vsmp->font = f;
SelectFont(f);
vsmp->lineheight = LineHeight();
vsmp->leading = Leading();
vsmp->charw = MaxCharWidth();
vsmp->set_atp = AsnFind("Bioseq-set.class");
vsmp->procid = ObjMgrProcLoad(OMPROC_EDIT, "NCBI DeskTop", "NCBI DeskTop",
0, 0, 0,0,(Pointer)vsmp, VSeqMgrGenFunc, PROC_PRIORITY_HIGHEST);
vsmp->proctype = OMPROC_EDIT;
vsmwp = VSMWinNew(vsmp);
vsmwp->w = w;
InsetRect(&rv, 2,2); /* allow space when clipping marquee */
LoadRect(&(vsmwp->rv), rv.left, rv.top, rv.right, rv.bottom);
omudp = ObjMgrAddUserData(0, vsmp->procid, OMPROC_EDIT, vsmwp->userkey);
omudp->userdata.ptrvalue = (Pointer)vsmwp;
omudp->messagefunc = VSeqMgrMsgFunc;
vsmwp->msgfunc = VSeqMgrMsgFunc;
ArrowCursor();
return TRUE;
}
/*****************************************************************************
*
* VSeqMgrPopulateMain(vsmwp)
*
*****************************************************************************/
static void get_viewer_position (VieweR viewer, Int4Ptr x, Int4Ptr y)
{
Int4 scale_x, scale_y;
BoxInfo port, world;
RecT v_iew;
ViewerBox (viewer, &world, &port, &v_iew, &scale_x, &scale_y);
*x = (port.left + port.right) / 2;
*y = (port.top + port.bottom) / 2;
}
static void NEAR VSeqMgrPopulateMain(VSMWinPtr vsmwp)
{
VieweR v = NULL;
RecT rw, rv;
BoxInfo box;
SegmenT picture, seg;
Int2 i, currnum, lineheight,right_frame;
Int4 x, y, top,width, bigtop, diffx, diffy;
ObjMgrDataPtr omdp, PNTR omdpp;
ObjMgrPtr omp;
AsnTypePtr atp;
WindoW w;
VSeqMgrPtr vsmp;
PrimitivE p;
OMUserDataPtr omudp;
VSMPictPtr vsmpp;
Boolean doit;
Int4 vwr_x, vwr_y, vwr_align;
/***
Message(MSG_OK, "In VSeqMgrPopulateMain");
***/
if (vsmwp == NULL) return;
vsmp = (VSeqMgrPtr)(vsmwp->vsmp);
w = vsmwp->w;
if (vsmp->set_atp == NULL)
vsmp->set_atp = AsnFind("Bioseq-set.class");
atp = vsmp->set_atp;
ObjectRect(w, &rw);
LoadRect(&rv, vsmp->xoff, vsmp->yoff, rw.right - rw.left - vsmp->x,
rw.bottom - rw.top - vsmp->y);
v = (VieweR) GetWindowExtra(w);
vwr_x = INT4_MIN;
vwr_y = INT4_MAX;
vwr_align = UPPER_LEFT;
if (v != NULL && vsmwp->picture != NULL) {
get_viewer_position (v, &(vwr_x), &(vwr_y));
vwr_align = MIDDLE_CENTER;
}
ResetViewer(v);
SetPosition(v, &rv);
LoadRect(&(vsmwp->rv), rv.left, rv.top, rv.right, rv.bottom);
InsetRect(&(vsmwp->rv), 2,2); /* allow space when clipping marquee */
right_frame = rv.right - rv.left + 1;
if (vsmwp->picture == NULL)
vsmwp->picture = CreatePicture();
else
{
while ((p = GetPrimitive(vsmwp->picture, 1)) != NULL)
{
UnlinkSegment((SegmenT)p);
}
}
picture = vsmwp->picture;
lineheight = vsmp->lineheight;
omp = vsmp->omp;
currnum = omp->currobj;
omdpp = omp->datalist;
x = 0;
y = 0;
bigtop = 0;
for (i = 0; i < currnum; i++, omdpp++)
{
omdp = *omdpp;
if ((omdp->parentptr == NULL) && (omdp->EntityID != 0))
{
doit = TRUE;
if ((! vsmp->show_cached) && (omdp->tempload == TL_CACHED))
doit = FALSE;
if ((! vsmp->show_clipboard) && (omdp->clipboard))
doit = FALSE;
if (doit)
{
omudp = ObjMgrGetUserData (omdp->EntityID, vsmwp->procid,
vsmwp->proctype, vsmwp->userkey);
if ((omudp == NULL) || (vsmp->update_all)) /* don't have one, or doing all */
omudp = VSMAddPictureToEntity(vsmwp, omdp->EntityID, 0);
vsmpp = (VSMPictPtr)(omudp->userdata.ptrvalue);
seg = vsmpp->s;
if ((seg != NULL) && (! vsmpp->deleted))
{
SegmentBox(seg, &box);
width = box.right - box.left + 1;
if ((x + width) > right_frame)
{
x = 0;
y = bigtop - lineheight;
}
diffx = x - box.left;
diffy = y - box.top;
OffsetSegment(seg, diffx, diffy);
top = y - (box.top - box.bottom + 1) - lineheight;
if (top < bigtop)
bigtop = top;
LinkSegment(picture, seg);
x += (width + lineheight);
}
}
}
}
vsmwp->populated = TRUE;
AttachPicture (v, picture, vwr_x, vwr_y, vwr_align, 1, 1, NULL);
SetViewerProcs(v, VSeqMgrClickProc, VSeqMgrDragProc, VSeqMgrReleaseProc, NULL);
SetViewerData(v, (Pointer)vsmwp, NULL);
if (Visible(w))
vsmwp->shown = TRUE; /* attach picture will show it */
else
vsmwp->shown = FALSE;
return;
}
/*****************************************************************************
*
* VSMWinNew(vsmp)
* adds a VSMWin to the chain
* if first one, labels as is_main_VSM
*
*****************************************************************************/
static VSMWinPtr NEAR VSMWinNew (VSeqMgrPtr vsmp)
{
VSMWinPtr vsmwp=NULL, tmp;
vsmwp = MemNew(sizeof(VSMWin));
vsmwp->vsmp = (Pointer)vsmp;
if (vsmp->wins == NULL)
{
vsmp->wins = vsmwp;
vsmwp->is_main_VSM = TRUE;
}
else
{
for (tmp = vsmp->wins; tmp->next != NULL; tmp = tmp->next)
continue;
tmp->next = vsmwp;
}
vsmwp->userkey = (++(vsmp->highest_userkey));
vsmwp->procid = vsmp->procid;
vsmwp->proctype = vsmp->proctype;
return vsmwp;
}
/*****************************************************************************
*
* VSMWinDelete(vsmwp, entityID, itemID, itemtype)
* deletes vsmwp from chain
*
*****************************************************************************/
static void NEAR VSMWinDelete(VSMWinPtr vsmwp, Uint2 entityID, Uint2 itemID, Uint2 itemtype)
{
VSeqMgrPtr vsmp;
VSMWinPtr tmp, prev=NULL, next=NULL;
VieweR v;
ObjMgrDataPtr omdp, PNTR omdpp;
ObjMgrPtr omp;
Int2 i, currnum;
if (vsmwp == NULL) return;
vsmp = VSeqMgrGet();
omp = vsmp->omp;
omdpp = omp->datalist;
currnum = omp->currobj;
if (vsmwp->entityID == 0)
{
for (i = 0; i < currnum; i++, omdpp++)
{
omdp = *omdpp;
if (omdp->EntityID)
ObjMgrFreeUserData(omdp->EntityID, vsmwp->procid, vsmwp->proctype, vsmwp->userkey);
}
}
ObjMgrFreeUserData(entityID, vsmwp->procid, vsmwp->proctype, vsmwp->userkey);
if (vsmwp->is_main_VSM) /* don't really delete */
{ /* if entityID != 0, could do a better refresh */
v = (VieweR)GetWindowExtra(vsmwp->w);
ResetViewer(v);
Hide(vsmwp->w);
vsmwp->picture = DeletePicture(vsmwp->picture);
vsmwp->in_process = FALSE;
vsmwp->populated = FALSE;
vsmwp->shown = FALSE;
return;
}
/* really delete */
Remove(vsmwp->w);
for (tmp = vsmp->wins; tmp != NULL; tmp = next)
{
next = tmp->next;
if (tmp == vsmwp)
{
if (prev == NULL)
vsmp->wins = next;
else
prev->next = next;
MemFree(tmp);
return;
}
}
return;
}
/*****************************************************************************
*
* VSeqMgrGetWinForW(w)
* finds the VSMWinPtr for w
* if w==NULL, finds the main_VSM VSMWinPtr
*
*****************************************************************************/
static VSMWinPtr NEAR VSeqMgrGetWinForW(WindoW w)
{
VSeqMgrPtr vsmp;
VSMWinPtr tmp;
vsmp = VSeqMgrGet();
for (tmp = vsmp->wins; tmp != NULL; tmp = tmp->next)
{
if (w == NULL)
{
if (tmp->is_main_VSM)
return tmp;
}
else
{
if (tmp->w == w)
return tmp;
}
}
return tmp;
}
/*****************************************************************************
*
* VSeqMgrGenFunc()
* General function to call from ObjMgr
*
*****************************************************************************/
Int2 LIBCALLBACK VSeqMgrGenFunc (Pointer ptr)
{
VSeqMgrPtr vsmp;
OMProcControlPtr ompcp;
VSMWinPtr vsmwp;
ompcp = (OMProcControlPtr)ptr;
vsmp = (VSeqMgrPtr)(ompcp->proc->procdata);
vsmwp = VSMWinNew(vsmp);
vsmwp->entityID = ompcp->input_entityID;
vsmwp->itemID = ompcp->input_itemID;
vsmwp->itemtype = ompcp->input_itemtype;
/* make the picture and the window */
return OM_MSG_RET_DONE;
}
/*****************************************************************************
*
* VSeqMgrMsgFunc()
* function to call on each DeskTop window by the ObjMgr
*
*****************************************************************************/
Int2 LIBCALLBACK VSeqMgrMsgFunc (OMMsgStructPtr ommsp)
{
OMUserDataPtr omudp;
VSMWinPtr vsmwp;
/***
Message(MSG_OK, "VSeqMgrMsgFunc [%d]", (int)message);
***/
omudp = (OMUserDataPtr)(ommsp->omuserdata);
vsmwp = (VSMWinPtr)(omudp->userdata.ptrvalue);
switch (ommsp->message)
{
case OM_MSG_DEL:
if (! ommsp->entityID) /* deleting desktop */
VSMWinDelete(vsmwp, ommsp->entityID, ommsp->itemID, ommsp->itemtype);
break;
case OM_MSG_CREATE:
VSMWinRefreshData(vsmwp, ommsp->entityID, ommsp->itemID, ommsp->itemtype);
break;
case OM_MSG_UPDATE:
break;
case OM_MSG_SELECT: /* add highlight code */
break;
case OM_MSG_DESELECT: /* add deselect code */
break;
case OM_MSG_CACHED:
break;
case OM_MSG_UNCACHED:
break;
case OM_MSG_TO_CLIPBOARD: /* this is just because no clipboard now */
Beep();
VSMWinRefreshData(vsmwp, ommsp->entityID, ommsp->itemID, ommsp->itemtype);
break;
default:
break;
}
return OM_MSG_RET_OK;
}
/*****************************************************************************
*
* VSMPictMsgFunc()
* function to call on each entity window by the ObjMgr
*
*****************************************************************************/
Int2 LIBCALLBACK VSMPictMsgFunc (OMMsgStructPtr ommsp)
{
OMUserDataPtr omudp;
VSMWinPtr vsmwp;
VSMPictPtr vsmpp=NULL;
Boolean do_add = FALSE, do_refresh = FALSE;
/***
Message(MSG_OK, "VSMPictMsgFunc [%d]", (int)message);
***/
omudp = (OMUserDataPtr)(ommsp->omuserdata);
vsmpp = (VSMPictPtr)(omudp->userdata.ptrvalue);
vsmwp = vsmpp->vsmwin;
switch (ommsp->message)
{
case OM_MSG_DEL:
if ((vsmwp->entityID == ommsp->entityID) &&
(vsmwp->itemID == ommsp->itemID) &&
(vsmwp->itemtype == ommsp->itemtype))
VSMWinDelete(vsmwp, ommsp->entityID, ommsp->itemID, ommsp->itemtype);
else if ((! ommsp->itemID) && (! ommsp->itemtype))
{
vsmpp->deleted = TRUE;
do_refresh = TRUE;
}
else
do_add = TRUE;
break;
case OM_MSG_CREATE: /* this is called because desktop function added picture */
break;
case OM_MSG_UPDATE:
do_add = TRUE;
break;
case OM_MSG_SELECT: /* add highlight code */
VSMPictSelect(vsmpp, ommsp->entityID, ommsp->itemID, ommsp->itemtype, TRUE);
break;
case OM_MSG_DESELECT: /* add deselect code */
VSMPictSelect(vsmpp, ommsp->entityID, ommsp->itemID, ommsp->itemtype, FALSE);
break;
case OM_MSG_CACHED:
do_add = TRUE;
break;
case OM_MSG_UNCACHED:
do_add = TRUE;
break;
case OM_MSG_TO_CLIPBOARD:
if (vsmwp->is_clipboard)
do_refresh = TRUE;
break;
default:
break;
}
if (do_add)
{
VSMAddPictureToEntity(vsmwp, ommsp->entityID, 0);
do_refresh = TRUE;
}
if (do_refresh)
{
VSMWinRefreshData(vsmwp, ommsp->entityID, ommsp->itemID, ommsp->itemtype);
}
return OM_MSG_RET_OK;
}
typedef struct vsmhlp {
Uint2 h_item, h_type;
VieweR h_v;
Int1 highlight;
} VSMHlp, PNTR VSMHlpPtr;
static Boolean VSMHighlightProc (SegmenT seg, PrimitivE prim, Uint2 segid, Uint2 primID, Uint2 primct, Pointer data)
{
VSMHlpPtr vhp;
vhp = (VSMHlpPtr)data;
if (segid == vhp->h_type)
{
if (primID == vhp->h_item)
{
HighlightSegment(vhp->h_v, seg, vhp->highlight);
return FALSE;
}
}
return TRUE;
}
/*****************************************************************************
*
* VSMPictSelect(vspp, entityID, itemID, itemtype, select)
*
*****************************************************************************/
static void NEAR VSMPictSelect(VSMPictPtr vsmpp, Uint2 entityID, Uint2 itemID, Uint2 itemtype, Boolean select)
{
VieweR v;
VSMHlp vh;
VSMWinPtr vsmwp;
if (vsmpp == NULL) return;
if (vsmpp->s == NULL) return;
if (vsmpp->vsmwin == NULL) return;
vsmwp = (VSMWinPtr)(vsmpp->vsmwin);
v = GetWindowExtra(vsmwp->w);
vh.h_v = v;
vh.h_item = itemID;
vh.h_type = itemtype;
if (select)
vh.highlight = OUTLINE_SEGMENT;
else
vh.highlight = PLAIN_SEGMENT;
if (! itemID)
HighlightSegment(v, vsmpp->s, vh.highlight);
else
ExploreSegment(vsmpp->s, (Pointer)(&vh), VSMHighlightProc);
return;
}
static void add_frame (SegmenT seg, Int4 left, Int4 top, Int4 right,
Int4 bottom, Uint2 primID)
{
AddInvFrame ( seg, left, top, right, bottom, primID );
}
typedef struct vsmgp {
SegmenT segs[20];
VSeqMgrPtr vsmp;
Int4 currline;
Uint1 level[OBJ_MAX];
SegmenT annotseg, descrseg;
} VSMGatherProcST, PNTR VSMGatherProcSTPtr;
static Boolean VSMGatherPictProc (GatherContextPtr gcp)
{
VSMGatherProcSTPtr vsmgp;
VSeqMgrPtr vsmp;
Char buf[81];
CharPtr tmp;
Int2 i, k, buflen;
Int4 top, lineheight, left, bottom, width, maxwidth;
SegmenT seg;
Uint1 shading, setcolor[3];
Uint1Ptr tcolor;
BioseqPtr bsp;
BioseqSetPtr bssp;
ObjMgrTypePtr omtp;
ValNode vn;
SeqFeatPtr sfp;
SeqAnnotPtr annot;
SeqGraphPtr sgp;
ValNodePtr desc;
ObjectIdPtr oip;
SeqIdPtr sip;
UserFieldPtr ufp;
UserObjectPtr uop;
SeqEntryPtr sep;
SeqEntryPtr oldsep;
vsmgp = (VSMGatherProcSTPtr)(gcp->userdata);
vsmp = vsmgp->vsmp;
lineheight = vsmp->lineheight;
top = vsmgp->currline * (lineheight + 2);
left = vsmp->charw * gcp->indent;
i = gcp->indent + 1; /* level 0 is the entity segment */
SelectFont(vsmp->font);
omtp = ObjMgrTypeFind(vsmp->omp, gcp->thistype, NULL, NULL);
sep = GetTopSeqEntryForEntityID (gcp->entityID);
oldsep = SeqEntrySetScope (sep);
switch (gcp->thistype)
{
case OBJ_SEQSUB:
case OBJ_SUBMIT_BLOCK:
if (vsmgp->level[gcp->thistype] < 2)
buflen = 40;
else
buflen = 80;
seg = CreateSegment(vsmgp->segs[gcp->indent], (Uint2)(gcp->thistype), 0);
vsmgp->segs[i] = seg;
bottom = top - lineheight;
AddAttribute(seg, COLOR_ATT, WHITE_COLOR,0, 0, 0, 0);
AddSegRect(seg, TRUE, (Uint2)(gcp->itemID));
AddAttribute(seg, COLOR_ATT, BLACK_COLOR,0, 0, 0, 0);
AddSegRect(seg, FALSE, (Uint2)(gcp->itemID));
if (gcp->thistype == OBJ_SEQSUB)
StringMove(buf, "Data Submission");
else
(*(omtp->labelfunc))(gcp->thisitem, buf, buflen, OM_LABEL_BOTH);
width = StringWidth(buf) + (2 * vsmp->charw);
/* this just forces the segment size */
add_frame(seg, left, top-2, (left+width), (top-lineheight+2), (Uint2)(gcp->itemID));
AddTextLabel(seg, left+(vsmp->charw), top, buf, vsmp->font,0,LOWER_RIGHT,(Uint2)(gcp->itemID));
vsmgp->currline--;
break;
case OBJ_SEQSUB_CONTACT:
case OBJ_SEQSUB_CIT:
if (vsmgp->level[gcp->thistype] < 2)
buflen = 40;
else
buflen = 80;
seg = CreateSegment(vsmgp->segs[gcp->indent], (Uint2)(gcp->thistype), 0);
vsmgp->segs[i] = seg;
bottom = top - lineheight;
if (gcp->thistype == OBJ_SEQSUB_CIT)
{
vn.choice = PUB_Sub;
vn.data.ptrvalue = gcp->thisitem;
vn.next = NULL;
omtp = ObjMgrTypeFind(vsmp->omp, OBJ_PUB, NULL, NULL);
tmp = StringMove(buf, "Cit: ");
(*(omtp->labelfunc))((Pointer)(&vn), tmp, (buflen - 5), OM_LABEL_CONTENT);
}
else
(*(omtp->labelfunc))(gcp->thisitem, buf, buflen, OM_LABEL_BOTH);
width = StringWidth(buf) + (2 * vsmp->charw);
/* this just forces the segment size */
add_frame(seg, left, top-2, (left+width), (top-lineheight+2), (Uint2)(gcp->itemID));
AddAttribute(seg, COLOR_ATT, BLACK_COLOR,0, 0, 0, 0);
AddTextLabel(seg, left+(vsmp->charw), top, buf, vsmp->font,0,LOWER_RIGHT,(Uint2)(gcp->itemID));
vsmgp->currline--;
break;
case OBJ_BIOSEQSET:
seg = CreateSegment(vsmgp->segs[gcp->indent], (Uint2)(gcp->thistype), 0);
vsmgp->segs[i] = seg;
bssp = (BioseqSetPtr)(gcp->thisitem);
bottom = top - lineheight;
if (gcp->indent > 3)
k = 3;
else
k = gcp->indent;
shading = (Uint1)(140 + (k * 20));
for (k = 0; k < 3; k++)
setcolor[k] = shading;
AddAttribute(seg, COLOR_ATT, setcolor,0, 0, 0, 0);
AddSegRect(seg, TRUE, (Uint2)(gcp->itemID));
(*(omtp->labelfunc))(gcp->thisitem, buf, 40, OM_LABEL_TYPE);
width = StringWidth(buf) + (2 * vsmp->charw);
/* this just forces the segment size */
add_frame(seg, left, top-2, (left+width), (top-lineheight+2), (Uint2)(gcp->itemID));
AddAttribute(seg, COLOR_ATT, BLUE_COLOR, 0, 0, 0,0);
AddTextLabel(seg, left+(vsmp->charw), top, buf, vsmp->font,0,LOWER_RIGHT,(Uint2)(gcp->itemID));
vsmgp->currline--;
break;
case OBJ_BIOSEQ:
seg = CreateSegment(vsmgp->segs[gcp->indent], (Uint2)(gcp->thistype), 0);
vsmgp->segs[i] = seg;
(*(omtp->labelfunc))(gcp->thisitem, buf, 40, OM_LABEL_CONTENT);
bsp = (BioseqPtr)(gcp->thisitem);
width = StringWidth(buf) + (2 * vsmp->charw);
maxwidth = width;
if (ISA_aa(bsp->mol))
tcolor = MAGENTA_COLOR;
else
tcolor = RED_COLOR;
/* just to force segment size */
AddAttribute(seg, COLOR_ATT , WHITE_COLOR, 0, 0,0,0);
if (vsmgp->level[OBJ_BIOSEQ] > 1)
k = 2;
else
k = 1;
AddSegRect(seg, TRUE, (Uint2)(gcp->itemID));
AddAttribute(seg, COLOR_ATT , tcolor, 0, 0,0,0);
AddSegRect(seg, FALSE, (Uint2)(gcp->itemID));
AddTextLabel(seg, left + vsmp->charw, top, buf, vsmp->font,0, LOWER_RIGHT,(Uint2)(gcp->itemID));
vsmgp->currline--;
if (k == 2)
{
(*(omtp->labelfunc))(gcp->thisitem, buf, 40, OM_LABEL_TYPE);
SelectFont(vsmp->font);
width = StringWidth(buf) + (3 * vsmp->charw);
if (width > maxwidth)
maxwidth = width;
AddTextLabel(seg, left + (2 * vsmp->charw), (top - lineheight), buf, vsmp->font,0, LOWER_RIGHT,(Uint2)(gcp->itemID));
vsmgp->currline--;
}
if (vsmgp->level[OBJ_BIOSEQ] == 3)
{
if (bsp->repr == Seq_repr_seg)
{
k = 3;
vn.choice = SEQLOC_MIX;
vn.data.ptrvalue = bsp->seq_ext;
vn.next = NULL;
SeqLocLabel(&vn, buf, 80, OM_LABEL_CONTENT);
SelectFont(vsmp->font);
width = StringWidth(buf) + (3 * vsmp->charw);
if (width > maxwidth)
maxwidth = width;
AddTextLabel(seg, left + (2 * vsmp->charw), (top - (2*lineheight)), buf, vsmp->font,0, LOWER_RIGHT,(Uint2)(gcp->itemID));
vsmgp->currline--;
}
}
add_frame(seg, left, top-2, (left+maxwidth), (top-(k * lineheight)+2), (Uint2)(gcp->itemID));
break;
case OBJ_SEQANNOT:
(*(omtp->labelfunc))(gcp->thisitem, buf, 40, OM_LABEL_BOTH);
if (vsmgp->level[OBJ_SEQANNOT] > 1) {
annot = (SeqAnnotPtr) gcp->thisitem;
if (annot != NULL) {
for (desc = annot->desc; desc != NULL; desc = desc->next) {
if (desc->choice == Annot_descr_name) {
StringCat (buf, " (");
StringNCat (buf, desc->data.ptrvalue, 35);
StringCat (buf, ")");
}
}
}
}
width = StringWidth(buf);
seg = CreateSegment(vsmgp->segs[gcp->indent], (Uint2)(gcp->thistype), 0);
vsmgp->segs[i] = seg;
AddAttribute(seg, COLOR_ATT, BLUE_COLOR, 0,0,0,0);
AddSegRect(seg, FALSE, (Uint2)(gcp->itemID));
AddTextLabel(seg, left, top, buf, vsmp->font,0, LOWER_RIGHT,(Uint2)(gcp->itemID));
add_frame(seg, left, top, (left+width), (top-lineheight), (Uint2)(gcp->itemID));
vsmgp->currline--;
break;
case OBJ_SEQALIGN:
if (vsmgp->level[OBJ_SEQALIGN] < 2)
buflen = 40;
else
buflen = 80;
seg = CreateSegment(vsmgp->segs[gcp->indent], (Uint2)(gcp->thistype), 0);
vsmgp->segs[i] = seg;
(*(omtp->labelfunc))(gcp->thisitem, buf, buflen, OM_LABEL_BOTH);
width = StringWidth(buf) + (2 * vsmp->charw);
AddAttribute(seg, COLOR_ATT , BLUE_COLOR, 0, 0,0,0);
AddTextLabel(seg, left + vsmp->charw, top, buf, vsmp->font,0, LOWER_RIGHT,(Uint2)(gcp->itemID));
add_frame(seg, left+vsmp->charw, top, (left+width), (top-lineheight), (Uint2)(gcp->itemID));
vsmgp->currline--;
break;
case OBJ_ANNOTDESC:
if (vsmgp->level[OBJ_ANNOTDESC] < 2)
buflen = 40;
else
buflen = 80;
seg = CreateSegment(vsmgp->segs[gcp->indent], (Uint2)(gcp->thistype), 0);
vsmgp->segs[i] = seg;
(*(omtp->labelfunc))(gcp->thisitem, buf, buflen, OM_LABEL_BOTH);
width = StringWidth(buf) + (2 * vsmp->charw);
add_frame(seg, left, top-2, (left+width), (top-lineheight+2), (Uint2)(gcp->itemID));
AddAttribute(seg, COLOR_ATT , CYAN_COLOR, 0, 0,0,0);
AddTextLabel(seg, left + vsmp->charw, top, buf, vsmp->font,0, LOWER_RIGHT,(Uint2)(gcp->itemID));
vsmgp->currline--;
break;
case OBJ_SEQGRAPH:
if (vsmgp->level[OBJ_SEQGRAPH] < 2)
buflen = 40;
else
buflen = 80;
seg = CreateSegment(vsmgp->segs[gcp->indent], (Uint2)(gcp->thistype), 0);
vsmgp->segs[i] = seg;
(*(omtp->labelfunc))(gcp->thisitem, buf, buflen, OM_LABEL_BOTH);
width = StringWidth(buf) + (2 * vsmp->charw);
AddAttribute(seg, COLOR_ATT , BLUE_COLOR, 0, 0,0,0);
AddTextLabel(seg, left + vsmp->charw, top, buf, vsmp->font,0, LOWER_RIGHT,(Uint2)(gcp->itemID));
vsmgp->currline--;
maxwidth = width;
k = 1;
sgp = (SeqGraphPtr) gcp->thisitem;
if (vsmgp->level[OBJ_SEQGRAPH] > 1 && sgp != NULL && sgp->loc != NULL) {
k++;
SeqLocLabel(sgp->loc, buf, buflen, OM_LABEL_CONTENT);
SelectFont(vsmp->font);
width = StringWidth(buf) + (3 * vsmp->charw);
if (width > maxwidth)
maxwidth = width;
AddTextLabel(seg, left + (2*vsmp->charw), (top-lineheight), buf, vsmp->font,0, LOWER_RIGHT,(Uint2)(gcp->itemID));
vsmgp->currline--;
}
add_frame(seg, left, top-2, (left+width), (top-(k*lineheight)+2), (Uint2)(gcp->itemID));
/* add_frame(seg, left+vsmp->charw, top, (left+width), (top-lineheight), (Uint2)(gcp->itemID)); */
break;
case OBJ_SEQFEAT:
if (vsmgp->level[OBJ_SEQFEAT] < 2)
buflen = 40;
else
buflen = 80;
seg = CreateSegment(vsmgp->segs[gcp->indent], (Uint2)(gcp->thistype), 0);
vsmgp->segs[i] = seg;
(*(omtp->labelfunc))(gcp->thisitem, buf, buflen, OM_LABEL_BOTH);
width = StringWidth(buf) + (2 * vsmp->charw);
AddAttribute(seg, COLOR_ATT , BLUE_COLOR, 0, 0,0,0);
AddTextLabel(seg, left + vsmp->charw, top, buf, vsmp->font,0, LOWER_RIGHT,(Uint2)(gcp->itemID));
vsmgp->currline--;
maxwidth = width;
k = 1;
if (vsmgp->level[OBJ_SEQFEAT] == 2)
{
k++;
sfp = (SeqFeatPtr)(gcp->thisitem);
SeqLocLabel(sfp->location, buf, buflen, OM_LABEL_CONTENT);
SelectFont(vsmp->font);
width = StringWidth(buf) + (3 * vsmp->charw);
if (width > maxwidth)
maxwidth = width;
AddTextLabel(seg, left + (2*vsmp->charw), (top-lineheight), buf, vsmp->font,0, LOWER_RIGHT,(Uint2)(gcp->itemID));
vsmgp->currline--;
if (vsmp != NULL && vsmp->extraLevel && sfp->product != NULL) {
k++;
StringCpy (buf, "product ");
SeqLocLabel(sfp->product, buf + 8, buflen - 8, OM_LABEL_CONTENT);
SelectFont(vsmp->font);
width = StringWidth(buf) + (3 * vsmp->charw);
if (width > maxwidth)
maxwidth = width;
AddTextLabel(seg, left + (2*vsmp->charw), (top-lineheight*2), buf, vsmp->font,0, LOWER_RIGHT,(Uint2)(gcp->itemID));
vsmgp->currline--;
}
if (vsmp != NULL && vsmp->extraLevel && sfp->data.choice == SEQFEAT_RNA && sfp->ext != NULL) {
/* uop = sfp->ext; */
uop = FindUopByTag (sfp->ext, "MrnaProteinLink");
if (uop->type != NULL && StringICmp (uop->type->str, "MrnaProteinLink") == 0) {
ufp = uop->data;
if (ufp != NULL && ufp->choice == 1) {
oip = ufp->label;
if (oip != NULL && oip->str != NULL && StringICmp (oip->str, "protein seqID") == 0) {
tmp = (CharPtr) ufp->data.ptrvalue;
if (tmp != NULL) {
sip = MakeSeqID (tmp);
if (sip != NULL) {
vn.choice = SEQLOC_WHOLE;
vn.data.ptrvalue = (Pointer) sip;
k++;
StringCpy (buf, "protein ");
SeqLocLabel(&vn, buf + 8, buflen - 8, OM_LABEL_CONTENT);
SelectFont(vsmp->font);
width = StringWidth(buf) + (3 * vsmp->charw);
if (width > maxwidth)
maxwidth = width;
AddTextLabel(seg, left + (2*vsmp->charw), (top-lineheight*(k-1)), buf, vsmp->font,0, LOWER_RIGHT,(Uint2)(gcp->itemID));
vsmgp->currline--;
SeqIdFree (sip);
}
}
}
}
}
}
}
add_frame(seg, left, top-2, (left+width), (top-(k*lineheight)+2), (Uint2)(gcp->itemID));
break;
case OBJ_SEQDESC:
if (vsmgp->level[OBJ_SEQDESC] < 2)
buflen = 40;
else
buflen = 80;
seg = CreateSegment(vsmgp->segs[gcp->indent], (Uint2)(gcp->thistype), 0);
vsmgp->segs[i] = seg;
(*(omtp->labelfunc))(gcp->thisitem, buf, buflen, OM_LABEL_BOTH);
width = StringWidth(buf) + (2 * vsmp->charw);
add_frame(seg, left, top-2, (left+width), (top-lineheight+2), (Uint2)(gcp->itemID));
AddAttribute(seg, COLOR_ATT , BLACK_COLOR, 0, 0,0,0);
AddTextLabel(seg, left + vsmp->charw, top, buf, vsmp->font,0, LOWER_RIGHT,(Uint2)(gcp->itemID));
vsmgp->currline--;
break;
default:
break;
}
SeqEntrySetScope (oldsep);
return TRUE;
}
/*****************************************************************************
*
* VSMEntityDraw(omdp)
*
*****************************************************************************/
SegmenT VSMEntityDraw (ObjMgrDataPtr omdp, VSMPictPtr vsmpp, VSeqMgrPtr vsmp)
{
VSMGatherProcST vsg;
GatherScope gs;
SegmenT top = NULL, seg;
CharPtr tmp=NULL;
Char buf[41];
ObjMgrTypePtr omtp;
Int2 width, expansion, i, width2;
Boolean maxexpansion = FALSE;
Int4 bottom, maxwidth;
Uint1 tcolor[3];
Boolean extraLevel = FALSE;
MemSet(&vsg, 0, sizeof(VSMGatherProcST));
MemSet(&gs, 0, sizeof(GatherScope));
MemSet(gs.ignore, (int)(TRUE), (size_t)OBJ_MAX);
gs.nointervals = TRUE;
gs.do_not_reload_from_cache = TRUE;
if (vsmpp->expansion < 0)
vsmpp->expansion = 0;
expansion = vsmpp->expansion;
switch (omdp->datatype)
{
case OBJ_SEQSUB:
if (expansion)
{
vsg.level[OBJ_SEQSUB] = 1;
vsg.level[OBJ_SUBMIT_BLOCK] = 1;
}
if (expansion > 1)
{
vsg.level[OBJ_SEQSUB_CONTACT] = 1;
vsg.level[OBJ_SEQSUB_CIT] = 1;
}
if (expansion > 2)
{
vsg.level[OBJ_SUBMIT_BLOCK] = 2;
vsg.level[OBJ_SEQSUB_CONTACT] = 2;
vsg.level[OBJ_SEQSUB_CIT] = 2;
}
case OBJ_BIOSEQ:
case OBJ_BIOSEQSET:
if (expansion)
{
vsg.level[OBJ_BIOSEQ] = 1;
vsg.level[OBJ_BIOSEQSET] = 1;
}
if (vsmp != NULL && vsmp->extraLevel) {
extraLevel = TRUE;
}
if (expansion > 1 && (! extraLevel)) {
expansion++;
}
if (expansion > 1)
{
vsg.level[OBJ_BIOSEQ] = 2;
vsg.level[OBJ_SEQDESC] = 1;
vsg.level[OBJ_SEQANNOT] = 1;
}
if (expansion > 2)
{
vsg.level[OBJ_BIOSEQ] = 2;
vsg.level[OBJ_SEQDESC] = 1;
vsg.level[OBJ_SEQANNOT] = 1;
vsg.level[OBJ_ANNOTDESC] = 1;
vsg.level[OBJ_SEQFEAT] = 1;
vsg.level[OBJ_SEQGRAPH] = 1;
vsg.level[OBJ_SEQALIGN] = 1;
}
if (expansion > 3)
{
vsg.level[OBJ_BIOSEQ] = 3;
vsg.level[OBJ_SEQDESC] = 2;
vsg.level[OBJ_SEQANNOT] = 2;
vsg.level[OBJ_ANNOTDESC] = 2;
vsg.level[OBJ_SEQFEAT] = 2;
vsg.level[OBJ_SEQGRAPH] = 2;
vsg.level[OBJ_SEQALIGN] = 2;
maxexpansion = TRUE;
}
if (expansion > 4)
vsmpp->expansion = 4;
break;
case OBJ_SEQANNOT:
if (expansion)
{
vsg.level[OBJ_SEQANNOT] = 1;
}
if (expansion > 1)
{
vsg.level[OBJ_SEQANNOT] = 1;
vsg.level[OBJ_ANNOTDESC] = 1;
vsg.level[OBJ_SEQFEAT] = 1;
vsg.level[OBJ_SEQGRAPH] = 1;
vsg.level[OBJ_SEQALIGN] = 1;
}
if (expansion > 2)
{
vsg.level[OBJ_ANNOTDESC] = 2;
vsg.level[OBJ_SEQFEAT] = 2;
vsg.level[OBJ_SEQGRAPH] = 2;
vsg.level[OBJ_SEQALIGN] = 2;
maxexpansion = TRUE;
}
if (expansion > 3)
vsmpp->expansion = 3;
break;
case OBJ_SEQFEAT:
if (expansion)
{
vsg.level[OBJ_SEQFEAT] = 2;
maxexpansion = TRUE;
}
if (expansion > 1)
vsmpp->expansion = 1;
break;
case OBJ_SEQALIGN:
if (expansion)
{
vsg.level[OBJ_SEQALIGN] = 2;
maxexpansion = TRUE;
}
if (expansion > 1)
vsmpp->expansion = 1;
break;
case OBJ_SEQGRAPH:
if (expansion)
{
vsg.level[OBJ_SEQGRAPH] = 2;
maxexpansion = TRUE;
}
if (expansion > 1)
vsmpp->expansion = 1;
break;
default:
vsmpp->expansion = 0;
maxexpansion = TRUE;
break;
}
for (i = 0; i < OBJ_MAX; i++)
{
if (vsg.level[i])
gs.ignore[i] = FALSE;
}
vsg.vsmp = vsmp;
/* default label */
top = CreateSegment(NULL, omdp->EntityID, 0);
omtp = ObjMgrTypeFind(vsmp->omp, omdp->datatype, NULL, NULL);
seg = CreateSegment(top, omdp->datatype, 0); /* 2nd level necessary if not gather */
vsg.segs[0] = seg;
if (omtp->label != NULL)
tmp = omtp->label;
else if (omtp->name != NULL)
tmp = omtp->name;
else
tmp = omtp->asnname;
width = LabelCopyExtra(buf, tmp, 40, NULL, ": ");
tmp = buf + width;
width = 40 - width;
(*(omtp->labelfunc))(omdp->dataptr, tmp, width, OM_LABEL_TYPE);
SelectFont(vsmp->font);
width = StringWidth(buf) + (3 * vsmp->charw) + 20;
maxwidth = width;
AddAttribute(seg, COLOR_ATT, WHITE_COLOR, 0, 0, 0,0);
AddSegRect(seg, TRUE, 0);
if (omdp->tempload == TL_CACHED)
{
tcolor[0] = 0;
tcolor[1] = 128;
tcolor[2] = 128;
AddAttribute(seg, COLOR_ATT, tcolor, 0, 0, 0,0);
}
else if (omdp->tempload == TL_LOADED)
{
tcolor[0] = 0;
tcolor[1] = 128;
tcolor[2] = 64;
AddAttribute(seg, COLOR_ATT, tcolor, 0, 0, 0,0);
}
else if (omdp->clipboard)
AddAttribute(seg, COLOR_ATT, RED_COLOR, 0, 0, 0,0);
else
AddAttribute(seg, COLOR_ATT, BLUE_COLOR, 0, 0, 0,0);
AddSegRect(seg, FALSE, 0);
bottom = (Int4)(vsmp->lineheight + (vsmp->lineheight/2));
AddTextLabel(seg, vsmp->charw, bottom, buf, vsmp->font,0,UPPER_RIGHT,0);
bottom -= vsmp->lineheight;
if ((*(omtp->labelfunc))(omdp->dataptr, buf, 40, OM_LABEL_CONTENT))
{
SelectFont(vsmp->font);
width2 = StringWidth(buf) + (2 * vsmp->charw);
if (width2 > maxwidth)
maxwidth = width2;
AddTextLabel(seg, vsmp->charw,bottom,buf, vsmp->font,0,UPPER_RIGHT,0);
}
add_frame(seg, 0, (3 * vsmp->lineheight), maxwidth, 0, 0);
bottom += vsmp->lineheight;
maxwidth -= vsmp->charw;
if (! maxexpansion)
{
AddAttribute(seg, COLOR_ATT, RED_COLOR, 0, 0, 0,0);
AddRectangle(seg, (Int4)(maxwidth-20), (Int4)(bottom + vsmp->lineheight), (Int4)(maxwidth - 12),
(Int4)(bottom+4), UP_ARROW, TRUE, (Uint2)VSM_PICT_UP_BUTTON);
/**
AddSymbol(seg, (Int4)(width-15), bottom, UP_TRIANGLE_SYMBOL, TRUE,
UPPER_CENTER, (Uint2) VSM_PICT_UP_BUTTON);
**/
}
if (vsmpp->expansion)
{
AddAttribute(seg, COLOR_ATT, GREEN_COLOR, 0, 0, 0,0);
AddRectangle(seg, (Int4)(maxwidth-8), (Int4)(bottom + vsmp->lineheight), (Int4)(maxwidth),
(Int4)(bottom+4), DOWN_ARROW, TRUE, (Uint2)VSM_PICT_DOWN_BUTTON);
}
GatherEntity(omdp->EntityID, &vsg, VSMGatherPictProc, &gs);
return top;
}
static Pointer LIBCALLBACK VSMFreePictureForEntity (Pointer ptr)
{
VSMPictPtr vsmpp;
if (ptr == NULL) return NULL;
vsmpp = (VSMPictPtr)ptr;
if (vsmpp->s != NULL)
{
UnlinkSegment(vsmpp->s);
DeleteSegment(vsmpp->s);
}
return MemFree(vsmpp);
}
/*****************************************************************************
*
* VSMAddPictureToEntity(vsmwp, entityID, expand)
* if segment with picture already present, just refreshes it
* else adds the new one
* expand increments or decrements the expansion of the picture by its value
*
*****************************************************************************/
static OMUserDataPtr NEAR VSMAddPictureToEntity (VSMWinPtr vsmwp, Uint2 entityID, Int2 expand)
{
OMUserDataPtr omudp;
VSMPictPtr vsmpp;
ObjMgrDataPtr omdp;
SegmenT seg=NULL;
ValNodePtr vnp;
Pointer ptr;
SelStructPtr ssp;
VSeqMgrPtr vsmp;
if (vsmwp == NULL) return NULL;
/* already have it? */
omudp = ObjMgrGetUserData (entityID, vsmwp->procid, vsmwp->proctype, vsmwp->userkey);
if (omudp != NULL) /* have it already */
{
vsmpp = (VSMPictPtr)(omudp->userdata.ptrvalue);
UnlinkSegment(vsmpp->s);
DeleteSegment(vsmpp->s);
vsmpp->s = NULL;
}
else
{
omudp = ObjMgrAddUserData(entityID, vsmwp->procid, vsmwp->proctype,
vsmwp->userkey);
vsmpp = MemNew(sizeof(VSMPict));
vsmpp->vsmwin = vsmwp;
vsmpp->entityID = entityID;
omudp->userdata.ptrvalue = (Pointer)vsmpp;
omudp->freefunc = VSMFreePictureForEntity;
omudp->messagefunc = VSMPictMsgFunc;
}
omdp = ObjMgrGetData(entityID);
vnp = omdp->choice;
ptr = omdp->dataptr;
vsmpp->expansion += expand;
vsmp = vsmwp->vsmp;
if (vsmp != NULL) {
vsmp->extraLevel = TRUE;
}
seg = VSMEntityDraw(omdp, vsmpp, vsmwp->vsmp);
if (seg == NULL)
Message(MSG_ERROR, "VSMAddSegmentToPicture: can't handle [%d] [%d]",
(int)(omdp->choicetype), (int)(omdp->datatype));
else
{
vsmpp->s = seg;
ssp = ObjMgrGetSelected();
while (ssp != NULL)
{
if (ssp->entityID == entityID)
{
VSMPictSelect(vsmpp, entityID, ssp->itemID, ssp->itemtype, TRUE);
}
ssp = ssp->next;
}
}
return omudp;
}
| [
"[email protected]"
] | |
dce0e43f200d96bd35bed8303519f06a5fb086bd | 9bb58be07d0469154d49f1ec5adda5df347ae3f4 | /Chopping/chopping/Classes/Native/UnityEngine_UnityEngine_UICharInfo.h | 9d6ed5e4e088bc7d6b83c694eefdc78de7c443ab | [] | no_license | k-ysu/UnitySample | 2af781838780f29dab0c04f64304f980345b753a | dd584e9fdabcd7967708ac7399e26320a635292e | refs/heads/master | 2020-04-06T06:25:00.788953 | 2015-07-08T20:49:42 | 2015-07-08T20:49:42 | 33,134,026 | 0 | 0 | null | null | null | null | UTF-8 | C | false | false | 382 | h | #pragma once
#include <stdint.h>
// System.ValueType
#include "mscorlib_System_ValueType.h"
// UnityEngine.Vector2
#include "UnityEngine_UnityEngine_Vector2.h"
// UnityEngine.UICharInfo
struct UICharInfo_t149
{
// UnityEngine.Vector2 UnityEngine.UICharInfo::cursorPos
Vector2_t43 ___cursorPos_0;
// System.Single UnityEngine.UICharInfo::charWidth
float ___charWidth_1;
};
| [
"[email protected]"
] | |
ac96b57e556f552e62ddba230bce593687aaafa9 | 4d0300263d28fb461f285cc2c3dfd7c51621cb4d | /external/pthreads-w32-2-8-0-release/tests/cancel6a.c | 644cd4a53258b1c15ac8ae332f520673a82830d2 | [
"LGPL-2.1-or-later",
"LicenseRef-scancode-free-unknown",
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"LicenseRef-scancode-other-copyleft",
"LGPL-2.1-only",
"MIT",
"LicenseRef-scancode-generic-cla"
] | permissive | coronalabs/corona | 6a108e8bfc8026e8c85e6768cdd8590b5a83bdc2 | 5e853b590f6857f43f4d1eb98ee2b842f67eef0d | refs/heads/master | 2023-08-30T14:29:19.542726 | 2023-08-22T15:18:29 | 2023-08-22T15:18:29 | 163,527,358 | 2,487 | 326 | MIT | 2023-09-02T16:46:40 | 2018-12-29T17:05:15 | C++ | UTF-8 | C | false | false | 4,233 | c | /*
* File: cancel6a.c
*
*
* Pthreads-win32 - POSIX Threads Library for Win32
* Copyright (C) 1998 Ben Elliston and Ross Johnson
* Copyright (C) 1999,2000,2001 Ross Johnson
*
* Contact Email: [email protected]
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* --------------------------------------------------------------------------
*
* Test Synopsis: Test double cancelation - asynchronous.
* Second attempt should fail (ESRCH).
*
* Test Method (Validation or Falsification):
* -
*
* Requirements Tested:
* -
*
* Features Tested:
* -
*
* Cases Tested:
* -
*
* Description:
* -
*
* Environment:
* -
*
* Input:
* - None.
*
* Output:
* - File name, Line number, and failed expression on failure.
* - No output on success.
*
* Assumptions:
* - have working pthread_create, pthread_self, pthread_mutex_lock/unlock
* pthread_testcancel, pthread_cancel, pthread_join
*
* Pass Criteria:
* - Process returns zero exit status.
*
* Fail Criteria:
* - Process returns non-zero exit status.
*/
#include "test.h"
/*
* Create NUMTHREADS threads in addition to the Main thread.
*/
enum {
NUMTHREADS = 4
};
typedef struct bag_t_ bag_t;
struct bag_t_ {
int threadnum;
int started;
/* Add more per-thread state variables here */
int count;
};
static bag_t threadbag[NUMTHREADS + 1];
void *
mythread(void * arg)
{
int result = ((int)PTHREAD_CANCELED + 1);
bag_t * bag = (bag_t *) arg;
assert(bag == &threadbag[bag->threadnum]);
assert(bag->started == 0);
bag->started = 1;
/* Set to known state and type */
assert(pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL) == 0);
assert(pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL) == 0);
/*
* We wait up to 10 seconds, waking every 0.1 seconds,
* for a cancelation to be applied to us.
*/
for (bag->count = 0; bag->count < 100; bag->count++)
Sleep(100);
return (void *) result;
}
int
main()
{
int failed = 0;
int i;
pthread_t t[NUMTHREADS + 1];
assert((t[0] = pthread_self()).p != NULL);
for (i = 1; i <= NUMTHREADS; i++)
{
threadbag[i].started = 0;
threadbag[i].threadnum = i;
assert(pthread_create(&t[i], NULL, mythread, (void *) &threadbag[i]) == 0);
}
/*
* Code to control or munipulate child threads should probably go here.
*/
Sleep(500);
for (i = 1; i <= NUMTHREADS; i++)
{
assert(pthread_cancel(t[i]) == 0);
assert(pthread_cancel(t[i]) == ESRCH);
}
/*
* Give threads time to run.
*/
Sleep(NUMTHREADS * 100);
/*
* Standard check that all threads started.
*/
for (i = 1; i <= NUMTHREADS; i++)
{
if (!threadbag[i].started)
{
failed |= !threadbag[i].started;
fprintf(stderr, "Thread %d: started %d\n", i, threadbag[i].started);
}
}
assert(!failed);
/*
* Check any results here. Set "failed" and only print output on failure.
*/
failed = 0;
for (i = 1; i <= NUMTHREADS; i++)
{
int fail = 0;
int result = 0;
/*
* The thread does not contain any cancelation points, so
* a return value of PTHREAD_CANCELED confirms that async
* cancelation succeeded.
*/
assert(pthread_join(t[i], (void **) &result) == 0);
fail = (result != (int) PTHREAD_CANCELED);
if (fail)
{
fprintf(stderr, "Thread %d: started %d: count %d\n",
i,
threadbag[i].started,
threadbag[i].count);
}
failed = (failed || fail);
}
assert(!failed);
/*
* Success.
*/
return 0;
}
| [
"[email protected]"
] | |
20c9c97d1bb8caf5e411acfb9840df212ee32ee8 | 40aeac4fc03811857ce2f392db05e6d9dc2079c6 | /3-quick_sort.c | 91cb203eefdb8de3cab14a2bcf13d37d44035345 | [] | no_license | daviddlhz/sorting_algorithms | d1d80ddb2999b4c0803ef7b970ea562c03f21e1f | 487c9dde31b4118e121f97d0c7ec5aad7889ac06 | refs/heads/master | 2022-11-09T00:58:15.262404 | 2020-06-18T03:55:56 | 2020-06-18T03:55:56 | 272,107,216 | 0 | 0 | null | null | null | null | UTF-8 | C | false | false | 1,597 | c | #include "sort.h"
/**
* quick_sort - sorts an array of integers in ascending order
* using the Quick sort algorithm.
*@array: array the integer for order.
*@size: size of array.
* Return: void.
*/
void quick_sort(int *array, size_t size)
{
if (!array || size < 2)
return;
quick(array, 0, size - 1, size);
}
/**
* change - swapping values of a array.
* @a: value one for swap.
* @b: value two for swap.
* Return: void.
*/
void change(int *a, int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}
/**
* partition - partition array between low and high index.
* @array: input array.
* @first_value: index of start of array.
* @last_value: index of end of array.
* @size: length of array.
* Return: Starting index plus one
*/
int partition(int *array, int first_value, int last_value, size_t size)
{
int p = array[last_value];
int i = first_value;
int j;
for (j = first_value; j < last_value; j++)
{
if (array[j] <= p)
{
change(&array[i], &array[j]);
if (i != j)
print_array(array, size);
i++;
}
}
change(&array[i], &array[last_value]);
if (i != j)
{
print_array(array, size);
}
return (i);
}
/**
* quick - Quick Sort with extra parameter size
* @array: input array.
* @first_value: index of start of array
* @last_value: index of end of array
* @size: size length of array
*/
void quick(int *array, int first_value, int last_value, size_t size)
{
if (first_value < last_value)
{
int pi = partition(array, first_value, last_value, size);
quick(array, first_value, pi - 1, size);
quick(array, pi + 1, last_value, size);
}
}
| [
"[email protected]"
] | |
a181b20b21c1a53d2702872ada0b977118f5346c | d8a1f83cb28f036688359fdef556442202d7b6d5 | /Yu Xian/SP1-Team5/SP1-Team5/player.h | f43e55fb49b147ac7de87848337222a04e28dd45 | [] | no_license | Darrus/SP1 | ff7784d18c0b6fa9a80d12640ffda3002d6d8501 | c551130b73e8735c1f48e28623b389675174c8bf | refs/heads/master | 2021-03-12T21:44:27.634742 | 2015-09-03T12:30:07 | 2015-09-03T12:30:27 | 40,592,627 | 0 | 2 | null | null | null | null | UTF-8 | C | false | false | 108 | h | #ifndef PLAYER_H
#define PLAYER_H
void movement(void);
void player(void);
void detect(int Y,int X);
#endif | [
"[email protected]"
] | |
5737b5449f445229951b0a39e237204c411ea10e | fefac5716839ed8765f8a2b421bc1bf40900f64f | /d09/ex04/ft_rot42.c | 69cecd313df5b546e98e74713046cd99cd97fab5 | [] | no_license | luizakhachatryan/42 | b883472b972234bddbd04d5252bcfae5af76916a | 352bcc9f192d1af7cc4f8aa3093265d039e2237f | refs/heads/master | 2022-12-13T04:56:04.589325 | 2020-09-17T16:51:20 | 2020-09-17T16:51:20 | null | 0 | 0 | null | null | null | null | UTF-8 | C | false | false | 1,146 | c | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_rot42.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: gtertysh <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2016/11/03 21:58:10 by gtertysh #+# #+# */
/* Updated: 2016/11/04 02:01:11 by gtertysh ### ########.fr */
/* */
/* ************************************************************************** */
char *ft_rot42(char *str)
{
char *begin;
begin = str;
while (*str)
{
if (*str >= 'A' && *str <= 'Z')
*str = (*str - 65 + 42) % 26 + 65;
else if (*str >= 'a' && *str <= 'z')
*str = (*str - 97 + 42) % 26 + 97;
str++;
}
return (begin);
}
| [
"[email protected]"
] | |
47e9ff0d6ba4cca34d5b01d19a4645a0de9f7fa4 | 4ef60e5057eb9bc66c854896ed45ae0b98b5e945 | /Dave/Libraries/XMC_Peripheral_Library_v2.1.4p1/XMCLib/src/xmc_common.c | 0d2d305e8aa1775e5a5a906d428b81a663cf7b29 | [
"BSD-3-Clause"
] | permissive | pfanchri/Bachelorarbeit | 70fdaa5d13386debfe72b63794b7523231c78edd | 27e598accb296d8dcd2970d2c30d4daef095b8a9 | refs/heads/master | 2021-01-23T14:05:16.409141 | 2016-10-07T07:38:41 | 2016-10-07T07:38:41 | 58,367,383 | 2 | 0 | null | null | null | null | UTF-8 | C | false | false | 6,600 | c | /**
* @file xmc_common.c
* @date 2016-01-12
*
* @cond
*********************************************************************************************************************
* XMClib v2.1.4 - XMC Peripheral Driver Library
*
* Copyright (c) 2015-2016, Infineon Technologies AG
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,are permitted provided that the
* following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following
* disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided with the distribution.
*
* Neither the name of the copyright holders nor the names of its contributors may be used to endorse or promote
* products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY,OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* To improve the quality of the software, users are encouraged to share modifications, enhancements or bug fixes with
* Infineon Technologies AG [email protected]).
*********************************************************************************************************************
*
* Change History
* --------------
*
* 2015-02-20:
* - Initial <br>
*
* @endcond
*
*/
#include "xmc_common.h"
/*******************************************************************************
* DATA STRUCTURES
*******************************************************************************/
struct list
{
struct list *next;
};
/*******************************************************************************
* API IMPLEMENTATION
*******************************************************************************/
#if defined(XMC_ASSERT_ENABLE) && !defined(XMC_USER_ASSERT_FUNCTION)
__WEAK void XMC_AssertHandler(const char *const msg, const char *const file, uint32_t line)
{
while(1)
{
/* Endless loop */
}
}
#endif
void XMC_LIST_Init(XMC_LIST_t *list)
{
*list = NULL;
}
void *XMC_LIST_GetHead(XMC_LIST_t *list)
{
return *list;
}
void *XMC_LIST_GetTail(XMC_LIST_t *list)
{
struct list *tail;
if (*list == NULL)
{
tail = NULL;
}
else
{
for (tail = (struct list *)*list; tail->next != NULL; tail = tail->next)
{
/* Loop through the list */
}
}
return tail;
}
void XMC_LIST_Add(XMC_LIST_t *list, void *item)
{
struct list *tail;
((struct list *)item)->next = NULL;
tail = (struct list *)XMC_LIST_GetTail(list);
if (tail == NULL)
{
*list = item;
}
else
{
tail->next = (struct list *)item;
}
}
void XMC_LIST_Remove(XMC_LIST_t *list, void *item)
{
struct list *right, *left;
if (*list != NULL)
{
left = NULL;
for(right = (struct list *)*list; right != NULL; right = right->next)
{
if(right == item)
{
if(left == NULL)
{
/* First on list */
*list = right->next;
}
else
{
/* Not first on list */
left->next = right->next;
}
right->next = NULL;
break;
}
left = right;
}
}
}
void XMC_LIST_Insert(XMC_LIST_t *list, void *prev_item, void *new_item)
{
if (prev_item == NULL)
{
((struct list *)new_item)->next = (struct list *)*list;
*list = new_item;
}
else
{
((struct list *)new_item)->next = ((struct list *)prev_item)->next;
((struct list *)prev_item)->next = (struct list *)new_item;
}
}
void XMC_PRIOARRAY_Init(XMC_PRIOARRAY_t *prioarray)
{
XMC_ASSERT("XMC_PRIOARRAY_Init: NULL pointer", prioarray != NULL);
/* Initialize head, next points to tail, previous to NULL and the priority is MININT */
prioarray->items[prioarray->size].next = prioarray->size + 1;
prioarray->items[prioarray->size].previous = -1;
prioarray->items[prioarray->size].priority = INT32_MAX;
/* Initialize tail, next points to NULL, previous is the head and the priority is MAXINT */
prioarray->items[prioarray->size + 1].next = -1;
prioarray->items[prioarray->size + 1].previous = prioarray->size;
prioarray->items[prioarray->size + 1].priority = INT32_MIN;
}
void XMC_PRIOARRAY_Add(XMC_PRIOARRAY_t *prioarray, int32_t item, int32_t priority)
{
int32_t next;
int32_t previous;
XMC_ASSERT("XMC_PRIOARRAY_Add: item out of range", (item >= 0) && (item < prioarray->size));
next = XMC_PRIOARRAY_GetHead(prioarray);
while (XMC_PRIOARRAY_GetItemPriority(prioarray, next) > priority)
{
next = XMC_PRIOARRAY_GetItemNext(prioarray, next);
}
previous = prioarray->items[next].previous;
prioarray->items[item].next = next;
prioarray->items[item].previous = previous;
prioarray->items[item].priority = priority;
prioarray->items[previous].next = item;
prioarray->items[next].previous = item;
}
void XMC_PRIOARRAY_Remove(XMC_PRIOARRAY_t *prioarray, int32_t item)
{
int32_t next;
int32_t previous;
XMC_ASSERT("XMC_PRIOARRAY_Add: item out of range", (item >= 0) && (item < prioarray->size));
next = prioarray->items[item].next;
previous = prioarray->items[item].previous;
prioarray->items[previous].next = next;
prioarray->items[next].previous = previous;
}
| [
"[email protected]"
] | |
d09fd5cdb4762a7220b32faca4989cdedc06c568 | c7622da2b6a7f314dc6b3fbc0043a0cd4d55b086 | /power-libperfmgr/power-helper.c | f46b802d0ccbf116b499927e7c1f340a8a56e4ea | [] | no_license | ResurrectionRemix-Devices/device_xiaomi_platina | 67da4eaa2bde159195c6bd3253913d5642c3f29c | 3aa06b0b96a81121a07717ff11689b435bdf8101 | refs/heads/pie | 2020-04-20T02:30:10.929673 | 2019-07-17T10:05:42 | 2019-07-17T10:05:42 | 168,573,291 | 2 | 3 | null | null | null | null | UTF-8 | C | false | false | 6,539 | c | /*
* Copyright (c) 2012-2013, The Linux Foundation. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
* * * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of The Linux Foundation nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#define LOG_NIDEBUG 0
#define LOG_TAG "[email protected]"
#include <errno.h>
#include <inttypes.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <dlfcn.h>
#include <stdlib.h>
#include <unistd.h>
#include <log/log.h>
#include "power-helper.h"
#ifndef RPM_SYSTEM_STAT
#define RPM_SYSTEM_STAT "/d/system_stats"
#endif
#ifndef WLAN_POWER_STAT
#define WLAN_POWER_STAT "/d/wlan0/power_stats"
#endif
#ifndef TAP_TO_WAKE_NODE
#define TAP_TO_WAKE_NODE "/proc/touchpanel/wake_gesture"
#endif
#define ARRAY_SIZE(x) (sizeof((x))/sizeof((x)[0]))
#define LINE_SIZE 128
const char *rpm_stat_params[MAX_RPM_PARAMS] = {
"count",
"actual last sleep(msec)",
};
const char *master_stat_params[MAX_RPM_PARAMS] = {
"Accumulated XO duration",
"XO Count",
};
struct stat_pair rpm_stat_map[] = {
{ RPM_MODE_XO, "RPM Mode:vlow", rpm_stat_params, ARRAY_SIZE(rpm_stat_params) },
{ RPM_MODE_VMIN, "RPM Mode:vmin", rpm_stat_params, ARRAY_SIZE(rpm_stat_params) },
{ VOTER_APSS, "APSS", master_stat_params, ARRAY_SIZE(master_stat_params) },
{ VOTER_MPSS, "MPSS", master_stat_params, ARRAY_SIZE(master_stat_params) },
{ VOTER_ADSP, "ADSP", master_stat_params, ARRAY_SIZE(master_stat_params) },
{ VOTER_SLPI, "SLPI", master_stat_params, ARRAY_SIZE(master_stat_params) },
};
const char *wlan_power_stat_params[] = {
"cumulative_sleep_time_ms",
"cumulative_total_on_time_ms",
"deep_sleep_enter_counter",
"last_deep_sleep_enter_tstamp_ms"
};
struct stat_pair wlan_stat_map[] = {
{ WLAN_POWER_DEBUG_STATS, "POWER DEBUG STATS", wlan_power_stat_params, ARRAY_SIZE(wlan_power_stat_params) },
};
static int sysfs_write(char *path, char *s)
{
char buf[80];
int len;
int ret = 0;
int fd = open(path, O_WRONLY);
if (fd < 0) {
strerror_r(errno, buf, sizeof(buf));
ALOGE("Error opening %s: %s\n", path, buf);
return -1 ;
}
len = write(fd, s, strlen(s));
if (len < 0) {
strerror_r(errno, buf, sizeof(buf));
ALOGE("Error writing to %s: %s\n", path, buf);
ret = -1;
}
close(fd);
return ret;
}
void __attribute__((weak)) set_device_specific_feature(__unused feature_t feature, __unused int state)
{
}
void set_feature(feature_t feature, int state) {
switch (feature) {
case POWER_FEATURE_DOUBLE_TAP_TO_WAKE:
sysfs_write(TAP_TO_WAKE_NODE, state ? "1" : "0");
break;
default:
break;
}
set_device_specific_feature(feature, state);
}
static int parse_stats(const char **params, size_t params_size,
uint64_t *list, FILE *fp) {
ssize_t nread;
size_t len = LINE_SIZE;
char *line;
size_t params_read = 0;
size_t i;
line = malloc(len);
if (!line) {
ALOGE("%s: no memory to hold line", __func__);
return -ENOMEM;
}
while ((params_read < params_size) &&
(nread = getline(&line, &len, fp) > 0)) {
char *key = line + strspn(line, " \t");
char *value = strchr(key, ':');
if (!value || (value > (line + len)))
continue;
*value++ = '\0';
for (i = 0; i < params_size; i++) {
if (!strcmp(key, params[i])) {
list[i] = strtoull(value, NULL, 0);
params_read++;
break;
}
}
}
free(line);
return 0;
}
static int extract_stats(uint64_t *list, char *file,
struct stat_pair *map, size_t map_size) {
FILE *fp;
ssize_t read;
size_t len = LINE_SIZE;
char *line;
size_t i, stats_read = 0;
int ret = 0;
fp = fopen(file, "re");
if (fp == NULL) {
ALOGE("%s: failed to open: %s Error = %s", __func__, file, strerror(errno));
return -errno;
}
line = malloc(len);
if (!line) {
ALOGE("%s: no memory to hold line", __func__);
fclose(fp);
return -ENOMEM;
}
while ((stats_read < map_size) && (read = getline(&line, &len, fp) != -1)) {
size_t begin = strspn(line, " \t");
for (i = 0; i < map_size; i++) {
if (!strncmp(line + begin, map[i].label, strlen(map[i].label))) {
stats_read++;
break;
}
}
if (i == map_size)
continue;
ret = parse_stats(map[i].parameters, map[i].num_parameters,
&list[map[i].stat * MAX_RPM_PARAMS], fp);
if (ret < 0)
break;
}
free(line);
fclose(fp);
return ret;
}
int extract_platform_stats(uint64_t *list) {
return extract_stats(list, RPM_SYSTEM_STAT, rpm_stat_map, ARRAY_SIZE(rpm_stat_map));
}
int extract_wlan_stats(uint64_t *list) {
return extract_stats(list, WLAN_POWER_STAT, wlan_stat_map, ARRAY_SIZE(wlan_stat_map));
}
| [
"[email protected]"
] | |
430a9723bbe976f1f2249a4a8c50aa11e94009de | e3ac6d1aafff3fdfb95159c54925aded869711ed | /Temp/StagingArea/Data/il2cppOutput/t549556860MD.h | 66b4655cda3ebc801fd42445fec49782e8485350 | [] | no_license | charlantkj/refugeeGame- | 21a80d17cf5c82eed2112f04ac67d8f3b6761c1d | d5ea832a33e652ed7cdbabcf740e599497a99e4d | refs/heads/master | 2021-01-01T05:26:18.635755 | 2016-04-24T22:33:48 | 2016-04-24T22:33:48 | 56,997,457 | 1 | 0 | null | null | null | null | UTF-8 | C | false | false | 1,609 | h | #pragma once
#include "il2cpp-config.h"
#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif
#include <stdint.h>
#include <assert.h>
#include <exception>
struct t549556860;
struct Il2CppObject;
struct t537683269;
struct t1363551830;
#include "codegen/il2cpp-codegen.h"
#include "Il2CppObject.h"
#include "IntPtr_t.h"
#include "t2528615.h"
#include "t1363551830.h"
extern "C" void m3387498975_gshared (t549556860 * __this, Il2CppObject * p0, IntPtr_t p1, const MethodInfo* method);
#define m3387498975(__this, p0, p1, method) (( void (*) (t549556860 *, Il2CppObject *, IntPtr_t, const MethodInfo*))m3387498975_gshared)(__this, p0, p1, method)
extern "C" t2528615 m3153722429_gshared (t549556860 * __this, t2528615 p0, Il2CppObject * p1, const MethodInfo* method);
#define m3153722429(__this, p0, p1, method) (( t2528615 (*) (t549556860 *, t2528615 , Il2CppObject *, const MethodInfo*))m3153722429_gshared)(__this, p0, p1, method)
extern "C" Il2CppObject * m1949743260_gshared (t549556860 * __this, t2528615 p0, Il2CppObject * p1, t1363551830 * p2, Il2CppObject * p3, const MethodInfo* method);
#define m1949743260(__this, p0, p1, p2, p3, method) (( Il2CppObject * (*) (t549556860 *, t2528615 , Il2CppObject *, t1363551830 *, Il2CppObject *, const MethodInfo*))m1949743260_gshared)(__this, p0, p1, p2, p3, method)
extern "C" t2528615 m4247751725_gshared (t549556860 * __this, Il2CppObject * p0, const MethodInfo* method);
#define m4247751725(__this, p0, method) (( t2528615 (*) (t549556860 *, Il2CppObject *, const MethodInfo*))m4247751725_gshared)(__this, p0, method)
| [
"[email protected]"
] | |
d879378b9751ea06ac6562745f96a9f7a1910b18 | e25c8b65c0115053b14f8ecffaea94a964eefa1f | /ds/open/world2/mainland1/map_37_41.c | 5b9f2fd2a071e96af9c2a4f97f44d024cfda8c74 | [] | no_license | zwshen/mudos-game-ds | c985b4b64c586bdc7347bd95d97ab12e78a2f20f | 07ea84ebdff5ee49cb482a520bdf1aaeda886cd0 | refs/heads/master | 2022-03-01T14:55:10.537294 | 2022-02-15T15:41:26 | 2022-02-15T15:41:26 | 244,925,365 | 4 | 1 | null | 2022-02-15T15:41:27 | 2020-03-04T14:44:49 | C | BIG5 | C | false | false | 401 | c | inherit ROOM;
void create()
{
set("short", "草地");
set("long", @LONG
LONG
);
set("exits",([
"west" : __DIR__"map_37_40",
"south" : __DIR__"map_38_41",
"north" : __DIR__"map_36_41",
"east" : __DIR__"map_37_42",
]));
set("outdoors","land");
setup();
set("map_long",1); //show map as long
replace_program(ROOM); //加其他函式xxx()時請拿掉此行
}
| [
"[email protected]"
] | |
2e2873e98d86cf12ec2f6357ee59c712eaf98249 | ef83b5de93967e6605ab23301600457f574f3f78 | /appdistsrc/github.com/acplt/rte/syslibs/functionblock/fb/include/fb_namedef.h | 75e4e59993705843f820efb40a813bac845d688c | [
"Apache-2.0"
] | permissive | gearboxworks/gearbox | 18438ce92efbe2b9c6d61862369ca4a35e7279f0 | 0180d4fc85ddfcb8462d4f238d1b4b790b2dcd48 | refs/heads/master | 2023-03-10T19:26:53.583933 | 2019-11-16T20:33:52 | 2019-11-16T20:34:34 | 168,762,574 | 3 | 2 | null | 2023-02-25T02:51:29 | 2019-02-01T21:28:53 | C | UTF-8 | C | false | false | 8,864 | h | /******************************************************************************
*** ***
*** iFBSpro - Funktionsbaustein-Model ***
*** ##################################### ***
*** ***
*** L T S o f t ***
*** Agentur für Leittechnik Software GmbH ***
*** Brabanterstr. 13 ***
*** D-50171 Kerpen ***
*** Tel : 02237/92869-2 ***
*** Fax : 02237/92869-9 ***
*** e-Mail : [email protected] ***
*** Internet : http://www.ltsoft.de ***
*** ***
*** ------------------------------------------------------------------- ***
*** ***
*** Implementierung des Funktionsbausteinsystems IFBSpro ***
*** RWTH, Aachen ***
*** LTSoft, Kerpen ***
*** ***
*******************************************************************************
* *
* Datei *
* ----- *
* fb_namedef.h *
* *
* Historie *
* -------- *
* 1998-02-22 Alexander Neugebauer: Erstellung, LTSoft, Kerpen *
* *
* Beschreibung *
* ------------ *
* Name-Definitionen der FB-Objekten *
* *
******************************************************************************/
#ifndef IFBS_INC_NAMES_ONLY
#include "libov/ov_config.h"
#endif
#ifndef _FB_NAMEDEF_H_
#define _FB_NAMEDEF_H_
#define KS_VERSION 2
#define ANZ_MAX_ARRAY_ELEM 75
#define FB_INSTANZ_CONTAINER "TechUnits"
#define FB_INSTANZ_CONTAINER_PATH "/TechUnits"
#define FB_TASK_CONTAINER "Tasks"
#define FB_TASK_CONTAINER_PATH "/Tasks"
#define FB_CONN_CONTAINER "Cons"
#define FB_CONN_CONTAINER_PATH "/Cons"
#define FB_URTASK "UrTask"
#define FB_URTASK_PATH "/Tasks/UrTask"
#define FB_LIBRARIES_CONTAINER "Libraries"
#define FB_LIBRARIES_CONTAINER_PATH "/Libraries"
#define FB_TOOL_LIBRARY "fbtool"
#define FB_TOOL_CONTAINER "fbtool"
#define FB_TOOL_CONTAINER_PATH "/fbtool"
#define FB_FB_PATH "/fb/functionblock"
#define OV_LIB_PATH "/acplt/ov/"
#define OV_ASSOC_PATH "/acplt/ov/association"
#define OV_CLASS_PATH "/acplt/ov/class"
#define OV_VARLIBS_PATH "/vendor/libraries"
#define FB_DBINFO "dbinfo"
#define FB_SERV_INFO_VAR "licinfo"
/* Logger */
#define FB_LOGGER_CONTAINER "serverinfo"
#define FB_LOGGER_CONTAINER_PATH "/serverinfo"
#define FB_LOGGER_NAME "logging"
#define FB_LOGGER_PATH "/serverinfo/logging"
/* FileUpload */
#define FB_UPLOAD_NAME "upload"
#define FB_UPLOAD_PATH "/serverinfo/upload"
/* DB and backup file extensions */
#define DB_FILEOVD_EX ".ovd"
#define DB_FILEBAC_EX ".bac"
#define IFBS_HOME_ENVPATH "IFBS_HOME"
#define ACPLT_HOME_ENVPATH "ACPLT_HOME"
/* fb/task: actimode */
#define FB_AM_OFF 0
#define FB_AM_ON 1
#define FB_AM_UNLINK 2
#define FB_AM_ONCE 3
#define FB_AM_CATCHUP 10
/* Error codes */
#define FB_ERR_ATPARSE 0x00020000
#define IFBS_OK_FLAG "OK"
#define IFBS_ERR_FLAG "ERR"
#define IFBS_WARNING_FLAG "WARNING"
/* Init output value */
#define IFBS_INIT_VALUE -989898
#ifndef IFBS_INC_NAMES_ONLY
#include "fb.h"
#ifdef __cplusplus
extern "C" {
#endif
/*
* Execute the child objects
*/
OV_DLLFNCEXPORT void fb_task_execChildObjects(
OV_INSTPTR_fb_task ptask,
OV_TIME *pltc
);
/*
* Set next proctime of the task object
*/
OV_DLLFNCEXPORT void fb_task_setNextProcTime(
OV_INSTPTR_fb_task ptask,
OV_TIME *pltc
);
/*
* Check whether the variable type is supportive of FB
*/
OV_DLLFNCEXPORT int fb_vartype_implemented(
OV_VAR_TYPE typ
);
/*
* Set variable value
*/
OV_DLLFNCEXPORT OV_RESULT fb_set_varvalue(
OV_INSTPTR_ov_object pobj,
const OV_ELEMENT *pelem,
const OV_ANY *pvarcurrprops,
OV_BOOL *changed
);
/*
* Trigger input get connections
* legacy function. could be called from derived libraries
*/
OV_DLLFNCEXPORT void fb_functionblock_triggerInpGetConnections(
OV_INSTPTR_fb_functionblock pfb
);
OV_DLLFNCEXPORT void fb_object_triggerInpGetConnections(
OV_INSTPTR_fb_object pfb
);
/*
* Trigger output send connections
* legacy function. could be called from derived libraries
*/
OV_DLLFNCEXPORT void fb_functionblock_triggerOutSendConnections(
OV_INSTPTR_fb_functionblock pfb
);
OV_DLLFNCEXPORT void fb_object_triggerOutSendConnections(
OV_INSTPTR_fb_object pfb
);
/*
* Call typemethod of functionblock
*/
OV_DLLFNCEXPORT OV_BOOL fb_functionblock_execTypeMethod(
OV_INSTPTR_fb_functionblock pfb,
OV_TIME *pltc
);
/*
* Create a connection object
* --------------------------
* OV_INSTPTR_fb_connection pcon;
* result = fb_connection_create("myconobj","/TechUnits/sum1","out","/TechUnits/sum2","in1",&pcon);
* if(result != OV_ERR_OK) {
* return result;
* }
* // turn on
* pcon->v_on = TRUE;
*/
OV_DLLFNCEXPORT OV_RESULT fb_connection_create(
OV_STRING identifier, /* Connection identifier "myconobj" */
OV_STRING sourceFB, /* Path source FB "/TechUnits/sum1" */
OV_STRING sourcePort, /* Source port identifier "out" */
OV_STRING targetFB, /* Path target FB "/TechUnits/sum2" */
OV_STRING targetPort, /* Target port identifier "in1" */
OV_INSTPTR_fb_connection *pcon /* Pointer connection object */
);
/**
* Gets the first connected fb_functionblock or fb_port from a given fb_functionblock / port and a variable name
* If a fb/port is given, the variableName will be ignored (aka can be NULL)
*
* @param this: functionblock or port to start the search
* @param getTarget: set to TRUE if you want a TargetObject (where the connection sets values), otherwise you get a Source (where the connection gets values from)
* @param skipInactiveCons: set to TRUE if you want to test only active connections
* @param variableName name of variable of an functionblock where the connection is connected
*/
OV_DLLFNCEXPORT OV_INSTPTR_fb_object fb_connection_getFirstConnectedObject(
const OV_INSTPTR_fb_object this,
const OV_BOOL getTarget,
const OV_BOOL skipInactiveCons,
const OV_STRING variableName
);
/*
* Get the envinroment
*/
OV_DLLFNCEXPORT char* fb___getenv(OV_STRING exepth);
OV_DLLFNCEXPORT void fb___addenvpath(const char *pEnvVar, const char *pth);
#ifdef __cplusplus
} // Extern "C"
#endif
#endif /* IFBS_INC_NAMES_ONLY */
/*
* Plattformen...
* --------------
*/
#if OV_SYSTEM_HPUX == 1
#define SERVER_SYSTEM "hpux"
#endif
#if OV_SYSTEM_LINUX == 1
#define SERVER_SYSTEM "linux"
#endif
#if OV_SYSTEM_NT == 1
#define SERVER_SYSTEM "nt"
#endif
#if OV_SYSTEM_OPENVMS == 1
#define SERVER_SYSTEM "openvms"
#endif
#if OV_SYSTEM_SOLARIS == 1
#define SERVER_SYSTEM "solaris"
#endif
#if OV_SYSTEM_MC164 == 1
#define SERVER_SYSTEM "mc164"
#endif
#endif
| [
"[email protected]"
] | |
c114638f56b7a652f029ae91c71fd19fd65fc96c | 6a8875d7041887db23c6150d603ba09db1e93e31 | /devices/gc864_modem.c | 065cc0ae6708c87eaa28103861be0d0a45f67e84 | [] | no_license | tiagosanchotene/proj-simone | 22eba35de15e3cde90a031cd62e46352ec6bad39 | 29d78fa872037cfb055dfec67aaa6323e9406909 | refs/heads/master | 2020-12-26T01:37:48.366274 | 2015-12-14T18:58:13 | 2015-12-14T18:58:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C | false | false | 11,015 | c | /* The License
*
* Copyright (c) 2015 Universidade Federal de Santa Maria
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
/*
* gc864_modem.c
*
* Created on: Aug 7, 2015
* Author: UFSM
*/
#include "AppConfig.h"
#include "BRTOS.h"
#include "gc864_modem.h"
#include "printf_lib.h"
#include "utils.h"
#include "terminal.h"
#include "terminal_commands.h"
#include "string.h"
#include "at_commands.h"
#include "simon-api.h"
#include "modem.h"
#ifdef _WIN32
#include <stdio.h>
#endif
static state_t modem_state = SETUP;
static char ip[16];
static char *hostname = NULL;
static char modem_BufferTxRx[64];
extern uint8_t mon_verbosity;
#define DEBUG_PRINT 1
#if DEBUG_PRINT
/* print outputs */
#undef PRINTS_ENABLED
#define PRINTS_ENABLED 1
#include "prints_def.h"
#define PRINT_INFO() PRINTF_P(PSTR("Line %d: "), __LINE__);
#define PRINT_P(...) printf_terminal_P(__VA_ARGS__);
#define PRINT(s) if(*(s)) { PRINT_INFO();printf_terminal((char*)(s));}
#define PRINT_BUF(s) if(*(s)) { PRINT_INFO();printf_terminal((char*)(s));}
#define PRINT_REPLY(...) printf_terminal(__VA_ARGS__);
#else
#define PRINT_P(...)
#define PRINT(...)
#define PRINT_BUF(...)
#define PRINT_REPLY(...)
#endif
#define UNUSED(x) (void)x;
#define DEBUG_PUTCHAR 0
#if DEBUG_PUTCHAR
#define DPUTCHAR(x) putchar_terminal(x);
#else
#define DPUTCHAR(x)
#endif
#define CONST const
#define MAX_RETRIES (3)
uint8_t Check_Connect_PPP(uint8_t retries);
/* return modem reply */
uint8_t modem_getchar(void)
{
uint8_t caracter;
if(OSQueuePend(MODEM_QUEUE, &caracter, MODEM_UART_TIMEOUT) == TIMEOUT)
{
return (uint8_t) (-1);
}
return (uint8_t)caracter;
}
static INT8U modem_get_reply(char *buf, uint16_t max_len)
{
uint8_t c;
uint8_t len = 0;
memset(buf,0x00,max_len); // clear buffer
while((c=modem_getchar()) != (uint8_t)-1)
{
*buf = c;
buf++;
len++;
if(--max_len <= 1)
{
break;
}
}
return len;
}
static void modem_get_reply_print(char *buf, uint16_t max_len)
{
modem_get_reply(buf, max_len);
if(mon_verbosity > 4 && is_terminal_idle()) PRINT_BUF(buf);
}
static void wait_modem_get_reply(uint16_t time)
{
DelayTask(time);
modem_get_reply(modem_BufferTxRx,(INT16U)sizeof(modem_BufferTxRx)-1);
}
#define MODEM_GET_REPLY(b) modem_get_reply((b), sizeof(b)-1);
#define MODEM_GET_REPLY_PRINT(b) modem_get_reply_print((b), (sizeof(b)-1));
INT8U is_modem_ok(void)
{
INT8U ok = FALSE;
modem_acquire();
if(mon_verbosity > 4 && is_terminal_idle()) PRINTS_PP(modem_init_cmd[AT]);
modem_printP(modem_init_cmd[AT]);
DelayTask(10);
MODEM_GET_REPLY_PRINT(modem_BufferTxRx);
if(modem_BufferTxRx[0] != 0)
{
if(strstr(modem_BufferTxRx, "OK"))
{
ok = TRUE;
}else
{
DelayTask(200);
OSCleanQueue(MODEM_QUEUE);
}
}
modem_release();
return ok;
}
uint8_t is_modem_ok_retry(uint8_t retries, uint16_t timeout)
{
while(is_modem_ok() == FALSE)
{
if(--retries == 0)
{
return FALSE;
}
DelayTask(timeout);
}
return TRUE;
}
uint8_t gc864_modem_init(void)
{
PRINTS_P(PSTR("Modem Init \r\n"));
if(modem_state == SETUP)
{
/* init MODEM_UART */
#if COLDUINO
#define BAUD(x) (x)
#endif
uart_init(MODEM_UART,BAUD(MODEM_BAUD),MODEM_UART_BUFSIZE,MODEM_MUTEX,MODEM_MUTEX_PRIO);
}
if(is_modem_ok_retry(MAX_RETRIES, 100) == FALSE)
{
return MODEM_ERR;
}
PRINTS_P(PSTR("Modem setup\r\n"));
modem_acquire();
/* setup */
modem_printP(modem_init_cmd[CREG]);
MODEM_GET_REPLY_PRINT(modem_BufferTxRx);
modem_printP(modem_init_cmd[CGDCONT]);
MODEM_GET_REPLY_PRINT(modem_BufferTxRx);
modem_printP(modem_init_cmd[GPRS]);
MODEM_GET_REPLY_PRINT(modem_BufferTxRx);
modem_release();
modem_state = INIT;
return MODEM_OK;
}
uint8_t gc864_modem_set_hostname(char *host)
{
hostname = host;
return MODEM_OK;
}
char* gc864_modem_get_hostname(void)
{
return hostname;
}
uint8_t gc864_modem_host_ip(void)
{
if(hostname == NULL)
{
return MODEM_ERR;
}
return MODEM_OK;
}
char* gc864_modem_get_ip(void)
{
return (char*)ip;
}
uint8_t gc864_modem_set_ip(char* _ip)
{
if(_ip == NULL)
{
return MODEM_ERR;
}
strcpy(ip,_ip);
return MODEM_OK;
}
uint8_t gc864_modem_send(char * dados, uint16_t tam)
{
uint16_t timeout = 0;
uint8_t retries = 0;
uint8_t send_ok = 0;
if(dados == NULL) goto exit;
if(hostname == NULL) goto exit;
*(dados+tam-1) = '\0'; // null terminate
if(mon_verbosity > 2) PRINTS_P(PSTR("Modem Send: \r\n"));
/* Flush queue first */
OSCleanQueue(MODEM_QUEUE);
/* check modem setup */
if(modem_state == SETUP)
{
if(gc864_modem_init() == MODEM_ERR)
{
if(mon_verbosity > 2) PRINTS_P(PSTR("Modem Init fail \r\n"));
goto exit;
}
}
/* check modem init */
if(modem_state == INIT)
{
if(is_modem_ok_retry(5, 10) == FALSE)
{
if(mon_verbosity > 2) PRINTS_P(PSTR("Modem GPRS is busy \r\n"));
goto exit; /* retry later */
}
if(Check_Connect_PPP(MAX_RETRIES) == FALSE)
{
if(mon_verbosity > 2) PRINTS_P(PSTR("Modem GPRS connection fail \r\n"));
goto exit;
}
}
try_again:
SNPRINTF_P(modem_BufferTxRx,sizeof(modem_BufferTxRx)-1,PSTR("AT#SKTD=0,80,%s,0,0\r\n"), hostname);
if(mon_verbosity > 2) PRINT(modem_BufferTxRx);
modem_printR(modem_BufferTxRx);
timeout = 0;
retries = 0;
do{
wait_modem_get_reply(100); // wait 100ms;
if(mon_verbosity > 2) PRINT_BUF(modem_BufferTxRx);
if(strstr((char *)modem_BufferTxRx,"CONNECT"))
{
goto send;
}
if(strstr((char *)modem_BufferTxRx,"NO CARRIER"))
{
if(++retries < MAX_RETRIES)
{
goto try_again;
}
break;
}
}while(++timeout < 20);
if(mon_verbosity > 2) PRINTS_P(PSTR("\r\nConnect fail\r\n"));
goto exit;
send:
if(mon_verbosity > 1) PRINT(dados);
modem_printR(dados);
timeout = 0;
send_ok = 0;
do
{
wait_modem_get_reply(10);
if(mon_verbosity > 2) PRINT_BUF(modem_BufferTxRx);
if(strstr((char *)modem_BufferTxRx,"OK"))
{
send_ok=1;
DelayTask(200);
OSCleanQueue(MODEM_QUEUE);
break;
}
}while(++timeout < 200); /* espera ate 2 segundo */
if(send_ok == 1)
{
if(mon_verbosity > 2) PRINTS_P(PSTR("\r\nsend ok\r\n"));
return MODEM_OK;
}else
{
if(mon_verbosity > 2) PRINTS_P(PSTR("\r\nsend fail\r\n"));
}
exit:
return MODEM_ERR;
}
uint8_t gc864_modem_receive(char* buff, uint16_t* len)
{
uint8_t ret = MODEM_ERR;
uint16_t size =(uint16_t) MIN(*len,SIZEARRAY(modem_BufferTxRx));
*len = 0;
if(size)
{
modem_acquire();
if(modem_BufferTxRx[0] !='\0')
{
ret = MODEM_OK;
memcpy(buff,modem_BufferTxRx,size);
if(size < SIZEARRAY(modem_BufferTxRx))
{
memcpy(modem_BufferTxRx,&modem_BufferTxRx[size],SIZEARRAY(modem_BufferTxRx)-size);
}
modem_get_reply(&modem_BufferTxRx[SIZEARRAY(modem_BufferTxRx)-size],size);
if(mon_verbosity > 4) PRINT_BUF(modem_BufferTxRx);
* len = size;
}
modem_release();
}
return (uint8_t)ret;
}
uint8_t gc864_modem_check_connection(void)
{
if(!is_modem_ok_retry(MAX_RETRIES, 100))
{
return MODEM_ERR;
}
return MODEM_OK;
}
const modem_driver_t gc864_modem_driver =
{
gc864_modem_init,
gc864_modem_receive,
gc864_modem_send,
gc864_modem_set_hostname,
gc864_modem_set_ip,
gc864_modem_check_connection
};
uint8_t Check_Connect_PPP(uint8_t retries)
{
DelayTask(100);
OSCleanQueue(MODEM_QUEUE);
do
{
/* check GPRS connection */
modem_printP(modem_init_cmd[GPRS]);
wait_modem_get_reply(100); // wait 100ms;
if(mon_verbosity > 0) PRINT_BUF(modem_BufferTxRx);
if(strstr((char *)modem_BufferTxRx,"#GPRS: 1") != NULL)
{
/* connected */
return TRUE;
}
else if(strstr((char *)modem_BufferTxRx,"#GPRS: 0") != NULL)
{
/* not connected */
if(--retries == 0) return FALSE;
modem_printP(modem_init_cmd[GPRS1]);
wait_modem_get_reply(500); // wait 500ms;
if(mon_verbosity > 0) PRINT_BUF(modem_BufferTxRx);
}else
{
/* no reply, buffer may be full */
if(--retries == 0) return FALSE;
OSCleanQueue(MODEM_QUEUE);
}
}while(TRUE);
return FALSE;
}
/* at commands */
modem_ret_t at_modem_init(void)
{
return gc864_modem_init();
}
modem_ret_t at_modem_open(INT8U host, char* dados)
{
uint8_t res;
if(host)
{
res = gc864_modem_set_hostname(dados);
if(mon_verbosity > 2)
{
PRINT("Host: ");
PRINT(dados);
}
}else
{
res = gc864_modem_set_ip((char*)dados);
if(mon_verbosity > 2)
{
PRINT("IP: ");
PRINT(dados);
}
}
res = Check_Connect_PPP(MAX_RETRIES);
return (res == TRUE ? MODEM_OK:MODEM_ERR);
}
modem_ret_t at_modem_send(char* dados)
{
return gc864_modem_send(dados, (uint16_t)strlen(dados));
}
modem_ret_t at_modem_receive(char* buff, uint16_t len)
{
uint16_t size = len;
if(buff == NULL) return MODEM_ERR;
/* try to receive */
if(gc864_modem_receive(buff,&size) == MODEM_OK)
{
*(buff+(size)) = '\0'; // null terminate
PRINT_BUF(buff);
}
PRINT("\r\n");
return MODEM_OK;
}
modem_ret_t at_modem_close(void)
{
PRINT("Close \r\n");
if(modem_state != CLOSE)
{
modem_state = CLOSE;
}
return MODEM_OK;
}
modem_ret_t at_modem_server(void)
{
PRINT_P(PSTR("NOT IMPLEMENTED \r\n"));
return MODEM_OK;
}
modem_ret_t at_modem_dns(char* param)
{
PRINT_P(PSTR("NOT IMPLEMENTED \r\n"));
return MODEM_OK;
}
modem_ret_t at_modem_time(void)
{
PRINT_P(PSTR("NOT IMPLEMENTED \r\n"));
return MODEM_OK;
}
| [
"[email protected]"
] | |
41fffae5ad9a51cfa0792600014bc349b059225f | 20b0a4d8ae9b3bbf52e06f64155653f4bbdb74a6 | /latterInsert.c | 4b5c8c6f0ea1d4e132241161d8b1c4cb6006d7fc | [] | no_license | yuyu232594/C-Program | 7606ca2a1b37332dea6152896f48cfa12c3019f8 | e5708443508a5ac011fdff2d33324e4e4a1ea08d | refs/heads/master | 2022-12-29T00:25:29.930039 | 2020-10-15T02:46:07 | 2020-10-15T02:46:07 | 262,900,266 | 1 | 1 | null | null | null | null | UTF-8 | C | false | false | 768 | c | //
// Created by 李闻瑜 on 2020/10/15.
//使用尾插法实现单链表
#include "stdio.h"
#include "stdlib.h"
typedef struct Point{
int element;
struct Point *next;
}node,*Linklist;
Linklist initLinklist(int num){
Linklist head=(Linklist)malloc(sizeof(node));
head->next=NULL;
for(int i=num;i>0;--i){
Linklist n=(Linklist)malloc(sizeof(node));
printf("please input the %d number",i);
scanf("%d",&(n->element));
n->next=head->next;
head->next=n;
}
return head;
}
void display(Linklist head){
Linklist temp=head;
while(temp->next){
temp=temp->next;
printf("%d\n",temp->element);
}
}
int main(){
Linklist head=initLinklist(10);
display(head);
return 0;
} | [
"[email protected]"
] | |
f7d45f73d4535c6b6db4c0880d86ca1cda5981bf | 2a3221b22c310ac533536a6c8a8d3e3d5b959667 | /BsdEthernet/sys/stddef.h | 33420b3cdca638fffc4ff4a7f1e1a06d88d3db57 | [
"BSD-2-Clause"
] | permissive | ahoka/esrtk | caf08057789e00c9f468e6ff9fa556aba2a2154d | bb5ff7f9caa22b6d6d91e660c6d78e471394a0cc | refs/heads/master | 2021-06-06T04:11:02.272680 | 2021-04-27T07:52:36 | 2021-04-27T07:52:36 | 37,784,499 | 1 | 0 | null | null | null | null | UTF-8 | C | false | false | 1,758 | h | /*-
* Copyright (c) 2002 Maxime Henrion <[email protected]>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $FreeBSD: releng/10.2/sys/sys/stddef.h 221476 2011-05-05 02:35:25Z obrien $
*/
#ifndef _SYS_STDDEF_H_
#define _SYS_STDDEF_H_
#include <sys/cdefs.h>
#include <sys/_null.h>
#include <machine/_types.h>
#ifndef _PTRDIFF_T_DECLARED
typedef __ptrdiff_t ptrdiff_t;
#define _PTRDIFF_T_DECLARED
#endif
#define offsetof(type, field) __offsetof(type, field)
#endif /* !_SYS_STDDEF_H_ */
| [
"[email protected]"
] | |
76de2b1eaba881d3045524423a5882698a10efa4 | f5f94d670be5169e86b116288fab28d9540e570a | /processing/colloid/include/miscellaneous.h | 1e8eb635229a7a0e9c9b2333224ae6e9884c0647 | [] | no_license | Bradleydi/processing | af6df07c130e97940d4fded1ec0af88860bb92fc | e4d874e6f0a46bb5784ef9e78906b331fd1fc3ad | refs/heads/master | 2020-07-10T19:49:22.459601 | 2016-08-28T07:41:04 | 2016-08-28T07:41:04 | 66,753,910 | 0 | 0 | null | null | null | null | UTF-8 | C | false | false | 5,027 | h | #ifndef MISCELLANEOUS_H
#define MISCELLANEOUS_H
#ifndef vGNUPLOT
#define vGNUPLOT 4.4
#endif
#ifndef vNEWGNUPLOT
#define vNEWGNUPLOT 4.0
#endif
#include <cstdio>
#include <cstdlib>
#include <unistd.h>
#define POW3(x) ((x)*(x)*(x))
#define Malloc(type, size) (type*)malloc((size)*sizeof(type))
#define Calloc(type, size) (type*)calloc((size), sizeof(type))
/* test whether the given pointer is NULL */
#define POINTER_NULL(pointer) if (pointer==NULL) { fprintf(stderr, "# Error: \"%s\" line %d\n# pointer \"%s\" is NULL!\n", __FILE__, __LINE__, #pointer); exit (1);}
/* test whether the given file is open */
#define FILE_NULL(file, filename) if (file==NULL) { fprintf(stderr, "# Error: \"%s\" line %d\n# cannot open file \"%s\"!\n", __FILE__, __LINE__, filename); exit (1);}
/* wrapper for binary reading and writing */
#define Fread(x, file, filename) if ( (int)fread(&x, sizeof(x), 1, file) != 1 ) { fprintf(stderr, "# Error: \"%s\" line %d\n# reading '%s' from file '%s' error!\n", __FILE__, __LINE__, #x, filename); exit (1);}
#define Fwrite(x, file, filename) if ( (int)fwrite(&x, sizeof(x), 1, file) != 1 ) { fprintf(stderr, "# Error: \"%s\" line %d\n# writing '%s' to file '%s' error!\n", __FILE__, __LINE__, #x, filename); exit (1);}
#define FreadN(x, n, file, filename) if ( (int)fread(x, sizeof(x[0]), n, file) != n ) { fprintf(stderr, "# Error: \"%s\" line %d\n# reading '%s' from file '%s' error!\n", __FILE__, __LINE__, #x, filename); exit (1);}
#define FwriteN(x, n, file, filename) if ( (int)fwrite(x, sizeof(x[0]), n, file) != n ) { fprintf(stderr, "# Error: \"%s\" line %d\n# writing '%s' to file '%s' error!\n", __FILE__, __LINE__, #x, filename); exit (1);}
#define Fclose(file, filename) if (fclose(file)!=0) { fprintf(stderr, "# Error: \"%s\" line %d\n# closing file %s failed!\n", __FILE__, __LINE__, filename); exit (1);}
/*! generate file name by given string and subfix.
* @param file
* type: const char*
* filename string used to generate a file name
* @param subfix
* type: const char*
* subfix of the generated file
* @return filename
* type: char*
* generated filename
*/
char* getfilename(const char*, const char*);
/*! pairwise summation of an array.
* This function could be used to avoid the summation of too many
* tiny numbers.
* @param n
* type: int
* number of elements of the array
* @param array
* type: double*
* the array
* @return sum
* type: double
* summation of the array
*/
double pairwise(int, double *);
inline void pERROR(const char * message)
{
(void)fprintf(stderr, "# Error: %s\n", message);
exit (1);
}
inline unsigned char FILE_EXIST(const char *file)
{
FILE *f = fopen(file, "r");
if ( f != NULL )
{
fclose (f);
return 1;
}
else
return 0;
}
/*! Average a two dimensional data set over angles about its center.
* data(x,y) sits at radius r = sqrt( (x-xc)^2 + (y-yc)^2 )
* from the center, (xc,yc). Let R be the integer part
* of r, and dR the fractional part. Then this point is
* averaged into result(R) with a weight 1-dR and into
* result(R+1) with a weight dR.
* @param nx
* type: int&
* size in x direction
* @param ny
* type: int&
* size in y direction
* @param data
* type: double*
* two dimensional array of any type except string or complex.
* data is saved in the form:
* data[i, j] = data[i+j*nx]
* @param nr
* type: int&
* size of result array
* @return avg
* type: double*
* result array averaged over angles as a function of radius from
* the center point, measured in pixels.
* written as a C translation of program written by
* David G. Grier, The University of Chicago, 7/30/92
*/
double * angleavg(int &, int &, double *, int &);
double * points2image(int &, double *, int &, int &,
double * =NULL, bool =true);
void linearfit(int, double *, double &, double &);
void sort(int, double *);
void Merge_sort(double *, double *, int, int);
void sort_int(int, int *);
void Merge_sort_int(int *, int *, int, int);
void getcluster(int Nedge, int *edges,
int *pNnode, int *pNcluster, int *cluster);
int* getframeindex(const char *string, int lower, int upper);
void show_matrix(int N, double *A);
/* Select */
double select_NR(int n, double *arr, int k);
double select(int n, double *arr, int k);
double select_wcp(int n, double *arr, double *copy, int k);
/* steady state detection */
void SSD(int N, double *y, int window, int *pNSS, int *SS);
/* batch job for SSD, with workspace allocated before calling
* workspace = Malloc(char, N)
*/
void SSD_batch(int N, double *y, int window, int *pNSS, int *SS,
char *workspace);
/* with statistics, i.e. mean & sigma*/
void SSD_statistics(int N, double *y, int window, int *pNSS, int *SS,
double *mean, double *sigma);
void SSD_statistics_batch(int N, double *y, int window, int *pNSS, int *SS,
double *mean, double *sigma, char *workspace);
#endif /* MISCELLANEOUS_H */
| [
"[email protected]"
] | |
90339de1d8d78fdb68eeae446bb08d01536b03ea | 6cc7a5ea75cfb23615a10e2ce5b9ea570e04948a | /double sum function.c.c | 16b9af9af9181c3846addfa94fc715ccbb635b0a | [] | no_license | nammi31/allMyCode | 330c5fd34b96f90a5019351028d530524a1bf6bc | 4bc34d73e43d4c34ad7ff410ff358aa7ef0a8df9 | refs/heads/master | 2020-06-27T00:18:40.354868 | 2019-07-31T06:58:45 | 2019-07-31T06:58:45 | 199,796,594 | 0 | 0 | null | null | null | null | UTF-8 | C | false | false | 274 | c |
#include<stdio.h>
double add(double num1,double num2);
int main()
{
double a,b,sum;
a=2.7,b=3.5;
sum=add(a,b);
printf("%lf",sum);
return 0;
}
double add(double num1,double num2)
{
double sum=num1+num2;
return sum;
}
| [
"[email protected]"
] | |
72de2ccd6a9cb828dfa573e3a310b5ee995b4b40 | db6903560e8c816b85b9adec3187f688f8e40289 | /VC98/Include/MSXMLDID.H | 9784b9ac5295b6817f7572d8cbb36216154431ec | [] | no_license | QianNangong/VC6Ultimate | 846a4e610859fab5c9d8fb73fa5c9321e7a2a65e | 0c74cf644fbdd38018c8d94c9ea9f8b72782ef7c | refs/heads/master | 2022-05-05T17:49:52.120385 | 2019-03-07T14:46:51 | 2019-03-07T14:46:51 | 147,986,727 | 4 | 1 | null | null | null | null | UTF-8 | C | false | false | 2,726 | h | //*********************************************************************
//* Microsoft Windows **
//* Copyright(c) Microsoft Corp., 1996-1997 **
//*********************************************************************
#ifndef __MSXMLDID_H__
#define __MSXMLDID_H__
#define DISPID_XOBJ_MIN 0x00010000
#define DISPID_XOBJ_MAX 0x0001FFFF
#define DISPID_XOBJ_BASE DISPID_XOBJ_MIN
#define DISPID_XMLELEMENTCOLLECTION DISPID_XOBJ_BASE
#define DISPID_XMLELEMENTCOLLECTION_LENGTH DISPID_XMLELEMENTCOLLECTION + 1
#define DISPID_XMLELEMENTCOLLECTION_NEWENUM DISPID_NEWENUM
#define DISPID_XMLELEMENTCOLLECTION_ITEM DISPID_XMLELEMENTCOLLECTION + 3
#define DISPID_XMLDOCUMENT DISPID_XMLELEMENTCOLLECTION + 100
#define DISPID_XMLDOCUMENT_ROOT DISPID_XMLDOCUMENT + 1
#define DISPID_XMLDOCUMENT_FILESIZE DISPID_XMLDOCUMENT + 2
#define DISPID_XMLDOCUMENT_FILEMODIFIEDDATE DISPID_XMLDOCUMENT + 3
#define DISPID_XMLDOCUMENT_FILEUPDATEDDATE DISPID_XMLDOCUMENT + 4
#define DISPID_XMLDOCUMENT_URL DISPID_XMLDOCUMENT + 5
#define DISPID_XMLDOCUMENT_MIMETYPE DISPID_XMLDOCUMENT + 6
#define DISPID_XMLDOCUMENT_READYSTATE DISPID_XMLDOCUMENT + 7
#define DISPID_XMLDOCUMENT_CREATEELEMENT DISPID_XMLDOCUMENT + 8
#define DISPID_XMLDOCUMENT_CHARSET DISPID_XMLDOCUMENT + 9
#define DISPID_XMLDOCUMENT_VERSION DISPID_XMLDOCUMENT + 10
#define DISPID_XMLDOCUMENT_DOCTYPE DISPID_XMLDOCUMENT + 11
#define DISPID_XMLDOCUMENT_DTDURL DISPID_XMLDOCUMENT + 12
#define DISPID_XMLELEMENT DISPID_XMLDOCUMENT + 100
#define DISPID_XMLELEMENT_TAGNAME DISPID_XMLELEMENT + 1
#define DISPID_XMLELEMENT_PARENT DISPID_XMLELEMENT + 2
#define DISPID_XMLELEMENT_SETATTRIBUTE DISPID_XMLELEMENT + 3
#define DISPID_XMLELEMENT_GETATTRIBUTE DISPID_XMLELEMENT + 4
#define DISPID_XMLELEMENT_REMOVEATTRIBUTE DISPID_XMLELEMENT + 5
#define DISPID_XMLELEMENT_CHILDREN DISPID_XMLELEMENT + 6
#define DISPID_XMLELEMENT_TYPE DISPID_XMLELEMENT + 7
#define DISPID_XMLELEMENT_TEXT DISPID_XMLELEMENT + 8
#define DISPID_XMLELEMENT_ADDCHILD DISPID_XMLELEMENT + 9
#define DISPID_XMLELEMENT_REMOVECHILD DISPID_XMLELEMENT + 10
#define DISPID_XMLNOTIFSINK DISPID_XMLELEMENT + 100
#define DISPID_XMLNOTIFSINK_CHILDADDED DISPID_XMLNOTIFSINK + 1
#endif // __MSXMLDID_H__
| [
"[email protected]"
] | |
f080c9551bfeb69b98f2550eab4f80c3a112bcba | 75769bea756af71dd3359711c0d96a08849ae7b8 | /cn/localhost01/lteenodeb/lte_rrc/sctp/sctp/basic/stack/mh/h/s_mhbld.h | c14a0d59fd00a705455e9a46d7d6b663a7b5b2aa | [] | no_license | windy-zzf/C_code_annalyze | ed986c6c24b7e410eae9790736209f8b0dbf15a8 | da038bcc9eda6a853f13bb39313917a16694271b | refs/heads/master | 2023-03-27T04:09:28.453216 | 2021-03-29T05:47:41 | 2021-03-29T05:47:41 | null | 0 | 0 | null | null | null | null | UTF-8 | C | false | false | 8,506 | h | /******************************************************************************
* FILE NAME:
* s_mhbld.h
*
* This file is part of Message Building module. It includes
* functions that process a sctp chunk before invoking fsm triggers
*
* DATE NAME REFERENCE REASON
* -----------------------------------------------------
* 02June 2000 Sandeep Mahajan - .Original Creation
* 27Aug01 gsheoran Rel 3.0
*
* Copyright (C) 2006 Aricent Inc . All Rights Reserved
*****************************************************************************/
#ifndef __FILE_sctp_mesg_build_SEEN__
#define __FILE_sctp_mesg_build_SEEN__
#ifdef __cplusplus
extern "C" {
#endif
void
sctp_insert_chksum(
sctp_U8bit *thisposition,
sctp_U8bit *origin,
sctp_checksum_et checksum );
/* SPR 20568 Starts for CSR 1-6658486 */
sctp_U8bit *
sctp_buffer_set_cookie(
sctp_U8bit *p_buf,
sctp_chunk_cookie_st *cookie );
sctp_U8bit *
sctp_buffer_get_cookie(
sctp_U8bit *p_buf,
sctp_chunk_cookie_st *cookie );
/* SPR 20568 Ends for CSR 1-6658486 */
sctp_U8bit *
sctp_build_common_header(
sctp_U8bit *P,
sctp_U16bit srcport,
sctp_U16bit dstport,
sctp_U32bit verification );
void
sctp_send_chunk_init(
sctp_tcb_st *p_ass,
sctp_sockaddr_st *p_from,
sctp_U16bit srcport,
sctp_U16bit dstport,
sctp_addrinfo_st *p_to,
sctp_U32bit init_tag,
sctp_U32bit init_tsn,
sctp_U16bit outstreams,
sctp_U16bit instreams,
sctp_U32bit rwnd,
sctp_U32bit num_addrs,
sctp_sockaddr_st *addr_list,
sctp_Boolean_t cookie_preservative_flag,
sctp_U32bit cookie_preservative_time,
sctp_suppaddr_st *p_supp_family,
sctp_U8bit *p_hostname,
sctp_U32bit adaption_ind );
void
sctp_send_chunk_initack(
sctp_tcb_st *p_ass,
sctp_sockaddr_st *p_from,
sctp_U16bit srcport,
sctp_U16bit dstport,
sctp_addrinfo_st *p_to,
sctp_U32bit tag,
sctp_chunk_cookie_st *cookie,
sctp_U16bit cookie_len,
sctp_Boolean_t unreco_param_present,
sctp_U16bit total_len,
sctp_U8bit *invalid_parameters,
sctp_U8bit *p_hostname,
sctp_U32bit adaption_ind );
void
sctp_send_chunk_cookie(
sctp_tcb_st *p_ass,
sctp_sockaddr_st *p_from,
sctp_U16bit srcport,
sctp_U16bit dstport,
sctp_addrinfo_st *p_to,
sctp_U32bit tag,
LIST *p_cookie_list,
sctp_U16bit cookiesize );
void
sctp_send_cookie_err_chunk_bundled(
sctp_tcb_st *p_ass,
sctp_sockaddr_st *p_from,
sctp_U16bit srcport,
sctp_U16bit dstport,
sctp_addrinfo_st *p_to,
sctp_U32bit tag,
LIST *p_cookie_list,
sctp_U16bit cookiesize,
sctp_U16bit cause_code,
sctp_U16bit cause_len,
sctp_U8bit *cause_info );
void
sctp_send_chunk_cookieack(
sctp_tcb_st *p_ass,
sctp_sockaddr_st *p_from,
sctp_U16bit srcport,
sctp_U16bit dstport,
sctp_addrinfo_st *p_to,
sctp_U32bit tag );
void
sctp_send_chunk_abort(
sctp_tcb_st *p_ass,
sctp_sockaddr_st *p_from,
sctp_U16bit srcport,
sctp_U16bit dstport,
sctp_sockaddr_st *p_to,
sctp_U32bit tag,
sctp_Boolean_t include_ecode,
sctp_U16bit cause_code,
sctp_U16bit cause_len,
sctp_U8bit *cause_info,
sctp_U8bit chunk_flag,
sctp_checksum_et checksum );
void
sctp_send_chunk_shutdowncomplete(
sctp_tcb_st *p_ass,
sctp_sockaddr_st *p_from,
sctp_U16bit srcport,
sctp_U16bit dstport,
sctp_addrinfo_st *p_to,
sctp_U32bit tag,
sctp_U8bit chunk_flag );
void
sctp_send_chunk_shutdownack(
sctp_tcb_st *p_ass,
sctp_sockaddr_st *p_from,
sctp_U16bit srcport,
sctp_U16bit dstport,
sctp_addrinfo_st *p_to,
sctp_U32bit tag );
void
sctp_send_chunk_shutdown(
sctp_tcb_st *p_ass,
sctp_sockaddr_st *p_from,
sctp_U16bit srcport,
sctp_U16bit dstport,
sctp_addrinfo_st *p_to,
sctp_U32bit tag,
sctp_U32bit cumtsn );
sctp_void_t sctp_get_confirmed_address(
sctp_tcb_st *p_ass,
sctp_sockaddr_st *p_to,
sctp_sockaddr_st *p_from );
void sctp_send_chunk_hb_path_verf( sctp_tcb_st *p_ass );
sctp_return_t sctp_get_addr_index_for_hb(
sctp_tcb_st *p_ass,
sctp_U32bit *addr_index );
void
sctp_send_chunk_heartbeat(
sctp_tcb_st *p_ass,
sctp_sockaddr_st *p_from,
sctp_U16bit srcport,
sctp_U16bit dstport,
sctp_U32bit dest_index,
sctp_U32bit tag );
void
sctp_send_chunk_heartbeatack(
sctp_tcb_st *p_ass,
sctp_sockaddr_st *p_from,
sctp_U16bit srcport,
sctp_U16bit dstport,
sctp_addrinfo_st *p_to,
sctp_U32bit tag,
sctp_U16bit heartbeatsize,
sctp_U8bit *heartbeat );
sctp_U8bit *
sctp_add_chunk_sack(
sctp_tcb_st *p_ass,
sctp_U8bit *P,
sctp_U32bit cumtsn,
sctp_U32bit arwnd,
LIST *sacklist,
sctp_U16bit num_duplicate_tsn,
sctp_U32bit *duplicat_tsn );
void
sctp_send_chunk_sack(
sctp_tcb_st *p_ass,
sctp_sockaddr_st *p_from,
sctp_U16bit srcport,
sctp_U16bit dstport,
sctp_addrinfo_st *p_to,
sctp_U32bit tag,
sctp_U32bit cumtsn,
sctp_U32bit arwnd,
LIST *sacklist,
sctp_U16bit num_duplicate_tsn,
sctp_U32bit *duplicat_tsn );
void
sctp_send_chunk_error(
sctp_tcb_st *p_ass,
sctp_sockaddr_st *p_from,
sctp_U16bit srcport,
sctp_U16bit dstport,
sctp_addrinfo_st *p_to,
sctp_U32bit tag,
sctp_U16bit cause_code,
sctp_U16bit cause_len,
sctp_U8bit *cause_info );
void
sctp_send_chunk_ecne(
sctp_tcb_st *p_ass,
sctp_sockaddr_st *p_from,
sctp_U16bit srcport,
sctp_U16bit dstport,
sctp_addrinfo_st *p_to,
sctp_U32bit tag,
sctp_U32bit lowest_tsn );
void
sctp_send_chunk_cwr(
sctp_tcb_st *p_ass,
sctp_sockaddr_st *p_from,
sctp_U16bit srcport,
sctp_U16bit dstport,
sctp_addrinfo_st *p_to,
sctp_U32bit tag,
sctp_U32bit lowest_tsn );
void
sctp_send_unrecognise_chunk_error(
sctp_tcb_st *p_ass,
sctp_sockaddr_st *p_from,
sctp_U16bit srcport,
sctp_U16bit dstport,
sctp_addrinfo_st *p_to,
sctp_U32bit tag,
sctp_U16bit cause_code,
sctp_U16bit cause_len,
sctp_U8bit *cause_info );
#ifdef SCTP_DYNAMIC_IP_SUPPORT
void
sctp_send_chunk_asconf(
sctp_tcb_st *p_ass,
sctp_sockaddr_st *p_from,
sctp_U16bit srcport,
sctp_U16bit dstport,
sctp_addrinfo_st *p_to,
sctp_U32bit tag,
sctp_addr_conf_st *p_addr_conf );
void
sctp_send_chunk_asconf_ack(
sctp_tcb_st *p_ass, /* SPR 20859*/
sctp_sockaddr_st *p_from,
sctp_U16bit srcport,
sctp_U16bit dstport,
sctp_addrinfo_st *p_to,
sctp_U32bit tag,
sctp_addr_conf_ack_st *p_addr_conf,
sctp_U8bit *p_buffer,
sctp_U32bit *p_buffer_len );
#endif
#ifdef __cplusplus
}
#endif
#endif /* __FILE_sctp_mesg_build_SEEN__ */
| [
"[email protected]"
] | |
6b2bac610f930ed71e9bb1ee0451f852145fbddd | 52f62927bb096e6cbc01bd6e5625a119fb35c1c5 | /avt/VisWindow/Interactors/Dolly3D.C | 82577869e7ee315318035c87f205c91ecb54a743 | [] | no_license | HarinarayanKrishnan/VisIt27RC_Trunk | f42f82d1cb2492f6df1c2f5bb05bbb598fce99c3 | 16cdd647ac0ad5abfd66b252d31c8b833142145a | refs/heads/master | 2020-06-03T07:13:46.229264 | 2014-02-26T18:13:38 | 2014-02-26T18:13:38 | null | 0 | 0 | null | null | null | null | UTF-8 | C | false | false | 9,259 | c | /*****************************************************************************
*
* Copyright (c) 2000 - 2013, Lawrence Livermore National Security, LLC
* Produced at the Lawrence Livermore National Laboratory
* LLNL-CODE-442911
* All rights reserved.
*
* This file is part of VisIt. For details, see https://visit.llnl.gov/. The
* full copyright notice is contained in the file COPYRIGHT located at the root
* of the VisIt distribution or at http://www.llnl.gov/visit/copyright.html.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the disclaimer below.
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the disclaimer (as noted below) in the
* documentation and/or other materials provided with the distribution.
* - Neither the name of the LLNS/LLNL nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL LAWRENCE LIVERMORE NATIONAL SECURITY,
* LLC, THE U.S. DEPARTMENT OF ENERGY OR CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*
*****************************************************************************/
// ************************************************************************* //
// Dolly3D.C //
// ************************************************************************* //
#include <Dolly3D.h>
#include <avtVector.h>
#include <avtMatrix.h>
#include <VisWindow.h>
#include <VisWindowInteractorProxy.h>
#include <vtkRenderWindowInteractor.h>
// ****************************************************************************
// Method: Dolly3D constructor
//
// Programmer: Eric Brugger
// Creation: December 27, 2004
//
// ****************************************************************************
Dolly3D::Dolly3D(VisWindowInteractorProxy &v) : VisitInteractor(v)
{
ctrlOrShiftPushed = false;
shouldSpin = false;
}
// ****************************************************************************
// Method: Dolly3D::OnTimer
//
// Purpose:
// Handles the timer event. For Dolly, this means the user has
// pressed a mouse key and that it is time to sample the mouse position
// to see if the view should be panned, zoomed or rotated.
//
// Programmer: Eric Brugger
// Creation: December 27, 2004
//
// Modifications:
// Kathleen Bonnell, Wed Jun 8 10:03:41 PDT 2011
// Use current EventPosition instead of last.
//
// ****************************************************************************
void
Dolly3D::OnTimer(void)
{
vtkRenderWindowInteractor *rwi = Interactor;
int Pos[2];
rwi->GetEventPosition(Pos);
bool matchedUpState = true;
switch (State)
{
case VTKIS_ROTATE:
RotateAboutFocus3D(Pos[0], Pos[1], true);
rwi->CreateTimer(VTKI_TIMER_UPDATE);
break;
case VTKIS_PAN:
PanCamera3D(Pos[0], Pos[1]);
rwi->CreateTimer(VTKI_TIMER_UPDATE);
break;
case VTKIS_ZOOM:
DollyCameraTowardFocus3D(Pos[0], Pos[1]);
rwi->CreateTimer(VTKI_TIMER_UPDATE);
break;
default:
matchedUpState = false;
break;
}
if (!matchedUpState && shouldSpin)
{
VisWindow *vw = proxy;
if(!vw->GetSpinModeSuspended())
{
if (vw->GetSpinMode())
{
OldX = spinOldX;
OldY = spinOldY;
RotateAboutFocus3D(spinNewX, spinNewY, true);
rwi->CreateTimer(VTKI_TIMER_UPDATE);
}
else
{
DisableSpinMode();
}
}
else if(vw->GetSpinMode())
{
// Don't mess with the camera, just create another timer so
// we keep getting into this method until spin mode is no
// longer suspended.
rwi->CreateTimer(VTKI_TIMER_UPDATE);
}
}
}
// ****************************************************************************
// Method: Dolly3D::StartLeftButtonAction
//
// Purpose:
// Handles the left button being pushed down. For Dolly, this means
// panning if the ctrl or shift is pushed, rotating otherwise. Also,
// this should start bounding box mode.
//
// Programmer: Eric Brugger
// Creation: December 27, 2004
//
// ****************************************************************************
void
Dolly3D::StartLeftButtonAction()
{
DisableSpinMode();
StartBoundingBox();
//
// If ctrl or shift is pushed, pan, otherwise rotate. Save which one we
// did so we can issue the proper "End.." statement when the button is
// released.
//
if (Interactor->GetControlKey()|| Interactor->GetShiftKey())
{
StartPan();
ctrlOrShiftPushed = true;
}
else
{
StartRotate();
ctrlOrShiftPushed = false;
}
}
// ****************************************************************************
// Method: Dolly3D::EndLeftButtonAction
//
// Purpose:
// Handles the left button being released. For Dolly, this means
// panning if the ctrl or shift button was held down while the left
// button was pushed, a rotation otherwise.
//
// Programmer: Eric Brugger
// Creation: December 27, 2004
//
// ****************************************************************************
void
Dolly3D::EndLeftButtonAction()
{
//
// We must issue the proper end state for either pan or rotate depending
// on whether the shift or ctrl button was pushed.
//
if (ctrlOrShiftPushed)
{
EndPan();
}
else
{
EndRotate();
EnableSpinMode();
}
EndBoundingBox();
IssueViewCallback();
}
// ****************************************************************************
// Method: Dolly3D::StartMiddleButtonAction
//
// Purpose:
// Handles the middle button being pushed down. For Dolly, this
// means zooming.
//
// Programmer: Eric Brugger
// Creation: December 27, 2004
//
// ****************************************************************************
void
Dolly3D::StartMiddleButtonAction()
{
DisableSpinMode();
StartBoundingBox();
StartZoom();
}
// ****************************************************************************
// Method: Dolly3D::EndMiddleButtonAction
//
// Purpose:
// Handles the middle button being released. For Dolly, this means
// ending a zoom.
//
// Programmer: Eric Brugger
// Creation: December 27, 2004
//
// ****************************************************************************
void
Dolly3D::EndMiddleButtonAction()
{
EndZoom();
EndBoundingBox();
IssueViewCallback();
}
// ****************************************************************************
// Method: Dolly3D::EnableSpinMode
//
// Purpose:
// Enables spin mode. This will determine if spin mode is appropriate,
// and make the correct calls to start it, if so.
//
// Programmer: Eric Brugger
// Creation: December 27, 2004
//
// ****************************************************************************
void
Dolly3D::EnableSpinMode(void)
{
VisWindow *vw = proxy;
if (vw->GetSpinMode())
{
shouldSpin = true;
//
// VTK will not be happy unless we enter one of its pre-defined modes.
// Timer seems as appropriate as any (there idea of spin is much
// different than ours). Also, set up the first timer so our spinning
// can get started.
//
StartTimer();
vtkRenderWindowInteractor *rwi = Interactor;
rwi->CreateTimer(VTKI_TIMER_UPDATE);
}
}
// ****************************************************************************
// Method: Dolly3D::DisableSpinMode
//
// Purpose:
// Disables spin mode if it is currently in action. This may be called
// at any time, even if spin mode is not currently on or even enabled.
//
// Programmer: Eric Brugger
// Creation: December 27, 2004
//
// ****************************************************************************
void
Dolly3D::DisableSpinMode(void)
{
if (shouldSpin)
{
EndTimer();
shouldSpin = false;
}
}
| [
"brugger@18c085ea-50e0-402c-830e-de6fd14e8384"
] | brugger@18c085ea-50e0-402c-830e-de6fd14e8384 |
920ad8a093650b7070d69ef25d4bf582d899b2d8 | 05b458a94b13328c4ab0bb474513e69c5f253ec0 | /analysis-sources/radare2-analysis/_cppstats/radare2/shlr/java/ops.h | 73d3b06f932120274db4dab865542f99680aa702 | [] | no_license | paulobernardoaf/dataset-files | c7b3a5f44f20a6809b6ac7c68b9098784d22ca52 | 6cc1726ee87e964dc05117673e50e3e364533015 | refs/heads/master | 2022-04-23T06:52:15.875641 | 2020-04-25T18:28:48 | 2020-04-25T18:28:48 | 253,626,694 | 0 | 0 | null | null | null | null | UTF-8 | C | false | false | 8,767 | h | #include <r_anal.h>
enum {
R_ANAL_JAVA_ILL_OP =-1,
R_ANAL_JAVA_NULL_OP = 0,
R_ANAL_JAVA_NOP = 1,
R_ANAL_JAVA_STORE_OP = 1 << 20,
R_ANAL_JAVA_LOAD_OP = 1 << 21,
R_ANAL_JAVA_REG_OP = 1 << 22,
R_ANAL_JAVA_OBJ_OP = 1 << 23,
R_ANAL_JAVA_STACK_OP = 1 << 25,
R_ANAL_JAVA_BIN_OP = 1 << 26,
R_ANAL_JAVA_CODE_OP = 1 << 27,
R_ANAL_JAVA_DATA_OP = 1 << 28,
R_ANAL_JAVA_UNK_OP = 1 << 29,
R_ANAL_JAVA_REP_OP = 1 << 30,
R_ANAL_JAVA_COND_OP = 1 << 31,
};
enum {
R_ANAL_JAVA_TYPE_REF_NULL = 0,
R_ANAL_JAVA_TYPE_REF_UNK = 1 << 1,
R_ANAL_JAVA_TYPE_REF = 1 << 2,
R_ANAL_JAVA_TYPE_SIGNED = 1 << 3,
R_ANAL_JAVA_TYPE_PRIM = 1 << 4,
R_ANAL_JAVA_TYPE_CONST = 1 << 5,
R_ANAL_JAVA_TYPE_STATIC = 1 << 6,
R_ANAL_JAVA_TYPE_VOLATILE = 1 << 7,
R_ANAL_JAVA_TYPE_PUBLIC = 1 << 8,
R_ANAL_JAVA_TYPE_BOOL = 1 << 10,
R_ANAL_JAVA_TYPE_BYTE = 1 << 11,
R_ANAL_JAVA_TYPE_SHORT = 1 << 12,
R_ANAL_JAVA_TYPE_INT32 = 1 << 13,
R_ANAL_JAVA_TYPE_INTEGER = 1 << 13,
R_ANAL_JAVA_TYPE_INT64 = 1 << 14,
R_ANAL_JAVA_TYPE_LONG = 1 << 14,
R_ANAL_JAVA_TYPE_FLOAT = 1 << 15,
R_ANAL_JAVA_TYPE_DOUBLE = 1 << 16,
R_ANAL_JAVA_TYPE_STRING = 1 << 17,
R_ANAL_JAVA_TYPE_CHAR = 1 << 18,
R_ANAL_JAVA_TYPE_VOID = 1 << 19,
};
enum {
R_ANAL_JAVA_CODEOP_JMP = 1 << 1 | R_ANAL_JAVA_CODE_OP,
R_ANAL_JAVA_CODEOP_CALL = 1 << 2 | R_ANAL_JAVA_CODE_OP,
R_ANAL_JAVA_CODEOP_RET = 1 << 3 | R_ANAL_JAVA_CODE_OP,
R_ANAL_JAVA_CODEOP_TRAP = 1 << 4 | R_ANAL_JAVA_CODE_OP,
R_ANAL_JAVA_CODEOP_SWI = 1 << 5 | R_ANAL_JAVA_CODE_OP,
R_ANAL_JAVA_CODEOP_IO = 1 << 6 | R_ANAL_JAVA_CODE_OP,
R_ANAL_JAVA_CODEOP_LEAVE = 1 << 7 | R_ANAL_JAVA_CODE_OP,
R_ANAL_JAVA_CODEOP_SWITCH = 1 << 8 | R_ANAL_JAVA_CODE_OP,
R_ANAL_JAVA_CODEOP_CJMP = R_ANAL_JAVA_COND_OP | R_ANAL_JAVA_CODE_OP | R_ANAL_JAVA_CODEOP_JMP,
R_ANAL_JAVA_CODEOP_EOB = R_ANAL_JAVA_CODEOP_JMP | R_ANAL_JAVA_CODEOP_RET | R_ANAL_JAVA_CODEOP_LEAVE | R_ANAL_JAVA_CODEOP_SWITCH,
};
enum {
R_ANAL_JAVA_RET_TYPE_REF_NULL = 1 << 10,
R_ANAL_JAVA_RET_TYPE_REF = 1 << 11 ,
R_ANAL_JAVA_RET_TYPE_PRIM = 1 << 12 ,
R_ANAL_JAVA_RET_TYPE_CONST = 1 << 13,
R_ANAL_JAVA_RET_TYPE_STATIC = 1 << 14,
};
enum {
R_ANAL_JAVA_COND_EQ = 1 << 11,
R_ANAL_JAVA_COND_NE = 1 << 12,
R_ANAL_JAVA_COND_GE = 1 << 13,
R_ANAL_JAVA_COND_GT = 1 << 14,
R_ANAL_JAVA_COND_LE = 1 << 15,
R_ANAL_JAVA_COND_LT = 1 << 16,
R_ANAL_JAVA_COND_AL = 1 << 17,
R_ANAL_JAVA_COND_NV = 1 << 18,
R_ANAL_JAVA_COND_NULL = 1 << 19,
};
enum {
R_ANAL_JAVA_BINOP_NEG = 0 | R_ANAL_JAVA_BIN_OP,
R_ANAL_JAVA_BINOP_XCHG = 1 << 1 | R_ANAL_JAVA_BIN_OP,
R_ANAL_JAVA_BINOP_CMP = 1 << 2 | R_ANAL_JAVA_BIN_OP,
R_ANAL_JAVA_BINOP_ADD = 1 << 3 | R_ANAL_JAVA_BIN_OP,
R_ANAL_JAVA_BINOP_SUB = 1 << 4 | R_ANAL_JAVA_BIN_OP,
R_ANAL_JAVA_BINOP_MUL = 1 << 6 | R_ANAL_JAVA_BIN_OP,
R_ANAL_JAVA_BINOP_DIV = 1 << 7 | R_ANAL_JAVA_BIN_OP,
R_ANAL_JAVA_BINOP_SHR = 1 << 8 | R_ANAL_JAVA_BIN_OP,
R_ANAL_JAVA_BINOP_SHL = 1 << 9 | R_ANAL_JAVA_BIN_OP,
R_ANAL_JAVA_BINOP_SAL = 1 << 10 | R_ANAL_JAVA_BIN_OP,
R_ANAL_JAVA_BINOP_SAR = 1 << 11 | R_ANAL_JAVA_BIN_OP,
R_ANAL_JAVA_BINOP_OR = 1 << 12 | R_ANAL_JAVA_BIN_OP,
R_ANAL_JAVA_BINOP_AND = 1 << 14 | R_ANAL_JAVA_BIN_OP,
R_ANAL_JAVA_BINOP_XOR = 1 << 15 | R_ANAL_JAVA_BIN_OP,
R_ANAL_JAVA_BINOP_NOT = 1 << 16 | R_ANAL_JAVA_BIN_OP,
R_ANAL_JAVA_BINOP_MOD = 1 << 17 | R_ANAL_JAVA_BIN_OP,
R_ANAL_JAVA_BINOP_ROR = 1 << 18 | R_ANAL_JAVA_BIN_OP,
R_ANAL_JAVA_BINOP_ROL = 1 << 19 | R_ANAL_JAVA_BIN_OP,
};
enum {
R_ANAL_JAVA_OBJOP_CAST = 1 << 0 | R_ANAL_JAVA_OBJ_OP,
R_ANAL_JAVA_OBJOP_CHECK = 1 << 1 | R_ANAL_JAVA_OBJ_OP,
R_ANAL_JAVA_OBJOP_NEW = 1 << 2 | R_ANAL_JAVA_OBJ_OP,
R_ANAL_JAVA_OBJOP_DEL = 1 << 3 | R_ANAL_JAVA_OBJ_OP,
R_ANAL_JAVA_OBJOP_SIZE = 1 << 4 | R_ANAL_JAVA_OBJ_OP,
};
enum {
R_ANAL_JAVA_LDST_FROM_REF = 1 << 1,
R_ANAL_JAVA_LDST_FROM_MEM = 1 << 1,
R_ANAL_JAVA_LDST_FROM_REG = 1 << 2,
R_ANAL_JAVA_LDST_FROM_STACK = 1 << 3,
R_ANAL_JAVA_LDST_FROM_CONST = 1 << 4,
R_ANAL_JAVA_LDST_FROM_VAR = 1 << 5,
R_ANAL_JAVA_LDST_INDIRECT_REF = 1 << 6,
R_ANAL_JAVA_LDST_INDIRECT_MEM = 1 << 6,
R_ANAL_JAVA_LDST_INDIRECT_REG = 1 << 7,
R_ANAL_JAVA_LDST_INDIRECT_STACK = 1 << 8,
R_ANAL_JAVA_LDST_INDIRECT_IDX = 1 << 9,
R_ANAL_JAVA_LDST_INDIRECT_VAR = 1 << 10,
R_ANAL_JAVA_LDST_TO_REF = 1 << 11,
R_ANAL_JAVA_LDST_TO_MEM = 1 << 11,
R_ANAL_JAVA_LDST_TO_REG = 1 << 12,
R_ANAL_JAVA_LDST_TO_STACK = 1 << 13,
R_ANAL_JAVA_LDST_TO_VAR = 1 << 14,
R_ANAL_JAVA_LDST_OP_PUSH = 1 << 15 ,
R_ANAL_JAVA_LDST_OP_POP = 1 << 16,
R_ANAL_JAVA_LDST_OP_MOV = 1 << 17 ,
R_ANAL_JAVA_LDST_OP_EFF_ADDR = 1 << 18,
};
enum {
R_ANAL_JAVA_LDST_LOAD_FROM_CONST_REF_TO_STACK = R_ANAL_JAVA_LDST_OP_PUSH |\
R_ANAL_JAVA_LOAD_OP |\
R_ANAL_JAVA_LDST_FROM_REF |\
R_ANAL_JAVA_LDST_FROM_CONST |\
R_ANAL_JAVA_LDST_TO_STACK |\
R_ANAL_JAVA_TYPE_REF,
R_ANAL_JAVA_LDST_LOAD_FROM_CONST_TO_STACK = R_ANAL_JAVA_LDST_OP_PUSH |\
R_ANAL_JAVA_LOAD_OP |\
R_ANAL_JAVA_LDST_FROM_CONST |\
R_ANAL_JAVA_LDST_TO_STACK,
R_ANAL_JAVA_LDST_LOAD_FROM_CONST_INDIRECT_TO_STACK = R_ANAL_JAVA_LDST_OP_PUSH |\
R_ANAL_JAVA_LOAD_OP |\
R_ANAL_JAVA_LDST_FROM_CONST |\
R_ANAL_JAVA_LDST_INDIRECT_IDX |\
R_ANAL_JAVA_LDST_TO_STACK,
R_ANAL_JAVA_LDST_LOAD_FROM_VAR_INDIRECT_TO_STACK = R_ANAL_JAVA_LDST_OP_PUSH |\
R_ANAL_JAVA_LOAD_OP |\
R_ANAL_JAVA_LDST_FROM_VAR |\
R_ANAL_JAVA_LDST_INDIRECT_IDX |\
R_ANAL_JAVA_LDST_TO_STACK,
R_ANAL_JAVA_LDST_LOAD_FROM_VAR_INDIRECT_TO_STACK_REF = R_ANAL_JAVA_LDST_OP_PUSH |\
R_ANAL_JAVA_LOAD_OP |\
R_ANAL_JAVA_LDST_FROM_VAR |\
R_ANAL_JAVA_LDST_INDIRECT_IDX |\
R_ANAL_JAVA_LDST_TO_STACK,
R_ANAL_JAVA_LDST_LOAD_FROM_VAR_TO_STACK = R_ANAL_JAVA_LDST_OP_PUSH |\
R_ANAL_JAVA_LOAD_OP |\
R_ANAL_JAVA_LDST_FROM_VAR |\
R_ANAL_JAVA_LDST_INDIRECT_IDX |\
R_ANAL_JAVA_LDST_TO_STACK,
R_ANAL_JAVA_LDST_LOAD_FROM_VAR_TO_STACK_REF = R_ANAL_JAVA_LDST_OP_PUSH |\
R_ANAL_JAVA_LOAD_OP |\
R_ANAL_JAVA_LDST_FROM_VAR |\
R_ANAL_JAVA_LDST_INDIRECT_IDX |\
R_ANAL_JAVA_LDST_TO_STACK,
R_ANAL_JAVA_LDST_LOAD_FROM_REF_INDIRECT_TO_STACK = R_ANAL_JAVA_LDST_OP_PUSH |\
R_ANAL_JAVA_LOAD_OP |\
R_ANAL_JAVA_LDST_FROM_REF |\
R_ANAL_JAVA_LDST_INDIRECT_IDX |\
R_ANAL_JAVA_LDST_TO_STACK,
R_ANAL_JAVA_LDST_LOAD_FROM_REF_INDIRECT_TO_STACK_REF = R_ANAL_JAVA_LDST_OP_PUSH |\
R_ANAL_JAVA_LOAD_OP |\
R_ANAL_JAVA_LDST_FROM_REF |\
R_ANAL_JAVA_LDST_INDIRECT_IDX |\
R_ANAL_JAVA_LDST_TO_STACK,
R_ANAL_JAVA_LDST_STORE_FROM_STACK_INDIRECT_TO_VAR = R_ANAL_JAVA_LDST_OP_PUSH |\
R_ANAL_JAVA_STORE_OP |\
R_ANAL_JAVA_LDST_FROM_STACK |\
R_ANAL_JAVA_LDST_INDIRECT_IDX |\
R_ANAL_JAVA_LDST_TO_VAR,
R_ANAL_JAVA_LDST_STORE_FROM_STACK_INDIRECT_TO_VAR_REF = R_ANAL_JAVA_LDST_OP_PUSH |\
R_ANAL_JAVA_STORE_OP |\
R_ANAL_JAVA_LDST_FROM_STACK |\
R_ANAL_JAVA_LDST_INDIRECT_IDX |\
R_ANAL_JAVA_LDST_TO_VAR,
R_ANAL_JAVA_LDST_STORE_FROM_STACK_TO_VAR = R_ANAL_JAVA_LDST_OP_PUSH |\
R_ANAL_JAVA_STORE_OP |\
R_ANAL_JAVA_LDST_FROM_STACK |\
R_ANAL_JAVA_LDST_TO_VAR,
R_ANAL_JAVA_LDST_STORE_FROM_STACK_TO_VAR_REF = R_ANAL_JAVA_LDST_OP_PUSH |\
R_ANAL_JAVA_STORE_OP |\
R_ANAL_JAVA_LDST_FROM_STACK |\
R_ANAL_JAVA_LDST_TO_VAR,
R_ANAL_JAVA_LDST_STORE_FROM_STACK_INDIRECT_TO_REF = R_ANAL_JAVA_LDST_OP_PUSH |\
R_ANAL_JAVA_STORE_OP |\
R_ANAL_JAVA_LDST_FROM_STACK |\
R_ANAL_JAVA_LDST_TO_REF,
R_ANAL_JAVA_LDST_STORE_FROM_STACK_INDIRECT_TO_REF_REF = R_ANAL_JAVA_LDST_OP_PUSH |\
R_ANAL_JAVA_STORE_OP |\
R_ANAL_JAVA_LDST_FROM_STACK |\
R_ANAL_JAVA_LDST_TO_REF,
R_ANAL_JAVA_LDST_LOAD_FROM_REF_TO_STACK = R_ANAL_JAVA_LDST_OP_PUSH |\
R_ANAL_JAVA_LOAD_OP |\
R_ANAL_JAVA_LDST_FROM_REF |\
R_ANAL_JAVA_LDST_TO_STACK |\
R_ANAL_JAVA_TYPE_PRIM,
R_ANAL_JAVA_LDST_LOAD_FROM_PRIM_VAR_TO_STACK = R_ANAL_JAVA_LDST_OP_PUSH |\
R_ANAL_JAVA_LOAD_OP |\
R_ANAL_JAVA_LDST_FROM_VAR |\
R_ANAL_JAVA_TYPE_PRIM,
R_ANAL_JAVA_LDST_LOAD_GET_STATIC = R_ANAL_JAVA_LDST_OP_PUSH |\
R_ANAL_JAVA_LOAD_OP |\
R_ANAL_JAVA_LDST_FROM_REF |\
R_ANAL_JAVA_LDST_TO_STACK |\
R_ANAL_JAVA_TYPE_REF,
R_ANAL_JAVA_LDST_STORE_PUT_STATIC = R_ANAL_JAVA_LDST_OP_POP |\
R_ANAL_JAVA_STORE_OP |\
R_ANAL_JAVA_LDST_FROM_STACK |\
R_ANAL_JAVA_LDST_TO_REF |\
R_ANAL_JAVA_TYPE_REF,
R_ANAL_JAVA_LDST_LOAD_GET_FIELD = R_ANAL_JAVA_LDST_OP_PUSH |\
R_ANAL_JAVA_LOAD_OP |\
R_ANAL_JAVA_LDST_FROM_REF |\
R_ANAL_JAVA_LDST_TO_STACK |\
R_ANAL_JAVA_TYPE_REF,
R_ANAL_JAVA_LDST_STORE_PUT_FIELD = R_ANAL_JAVA_LDST_OP_POP |\
R_ANAL_JAVA_STORE_OP |\
R_ANAL_JAVA_LDST_FROM_STACK |\
R_ANAL_JAVA_LDST_TO_REF |\
R_ANAL_JAVA_TYPE_REF,
};
| [
"[email protected]"
] | |
797c6590fb2d2658c755f23778a55d326a4978f0 | 3754bb109f1ca7e59d1ba5aa9b7c7031e7a6c9c9 | /MIMO_mm-wave_4x4_5b/SW/src/tx_driver.c | eb93f040dabe1e330eb67047238423512b8d45a6 | [] | no_license | tianyuez/MIMORPH | 4c3355a498a0b48aa9e223367b74159477dbaa9d | d634aa227a0fc683c20e3901565dc56284154869 | refs/heads/master | 2023-09-03T06:53:44.997795 | 2021-10-28T08:12:14 | 2021-10-28T08:12:14 | 430,055,054 | 1 | 0 | null | 2021-11-20T08:59:20 | 2021-11-20T08:59:19 | null | UTF-8 | C | false | false | 4,135 | c | /*
* tx_driver.c
*
* Created on: 25 nov. 2019
* Author: rruiz
*/
#include "tx_driver.h"
int reset_gpio[MAX_DAC] = {
0, 1, 2, 3, 4, 5, 6, 7
};
int loopback_gpio[MAX_DAC] = {
8, 9, 10, 11, 12, 13, 14, 15
};
int localstart_gpio[MAX_DAC] = {
16, 17, 18, 19, 20, 21, 22, 23
};
int globalstart_gpio = 24;
int configSiversGPIOtx(convData_t* cmdArrgs){
#ifndef U_WAVE
u32 P=cmdArrgs[0].u;
u32 M=cmdArrgs[1].u;
u32 N= cmdArrgs[2].u;
u32 L = cmdArrgs[3].u;
u32 T_INIT= cmdArrgs[4].u;
u32 T_HIGH= cmdArrgs[5].u;
u32 enable= cmdArrgs[6].u;
u32 packet = (L)<<27 | (N)<<17 | (M)<<10 | (P);
printf("Setting configuration for SIVERS GPIO TX: %d %d %d %d %d %d \n",P, M, N, L,T_INIT,T_HIGH);
Xil_Out32(XPAR_TX_DATAPATH_DAC_BLOCK0_TILE0_SIVERS_GPIO_0_S00_AXI_BASEADDR, packet);
usleep(10);
packet= (enable)<<23|(T_HIGH)<<16 | T_INIT;
Xil_Out32(XPAR_TX_DATAPATH_DAC_BLOCK0_TILE0_SIVERS_GPIO_0_S00_AXI_BASEADDR+0x04, packet);
return XRFDC_SUCCESS;
#endif
}
int LoadFIFO(int channels,u32 size, int16_t *buf) {
int ret;
int dac=0;
int tile_id;
for (dac = 0; dac < MAX_DAC; dac++) {
if ((channels & (1 << dac))) {
ret = set_gpio(localstart_gpio[dac] + GPIO_BANK_OFFSET, 0);
if (ret) {
printf("Unable to re-set loopback GPIO value\n");
return XRFDC_FAILURE;
}
/* Disable local start gpio */
ret = set_gpio(loopback_gpio[dac] + GPIO_BANK_OFFSET, 0);
if (ret) {
printf("Unable to re-set loopback GPIO value\n");
return XRFDC_FAILURE;
}
ret = set_gpio(reset_gpio[dac] + GPIO_BANK_OFFSET, 1);
if (ret) {
printf("Unable to reset Fifo GPIO value\n");
return XRFDC_FAILURE;
}
usleep(100);
ret = set_gpio(reset_gpio[dac] + GPIO_BANK_OFFSET, 0);
if (ret) {
printf("Unable to reset Fifo GPIO value\n");
return XRFDC_FAILURE;
}
tile_id = (dac / MAX_DAC);
ret = set_gpio(localstart_gpio[dac] + GPIO_BANK_OFFSET, 1);
if (ret) {
printf("Unable to quit localstart GPIO value\n");
return XRFDC_FAILURE;
}
}
else{
ret = set_gpio(localstart_gpio[dac] + GPIO_BANK_OFFSET, 0);
if (ret) {
printf("Unable to re-set loopback GPIO value\n");
return XRFDC_FAILURE;
}
}
}
/* Trigger DMA */
ret = SendPacketsDMA(buf, size);
if (ret) {
printf("Failed to send data\n");
return XRFDC_FAILURE;
}
usleep(100000);
for (dac = 0; dac < MAX_DAC; dac++) {
if ((channels & (1 << dac))) {
ret = set_gpio(loopback_gpio[dac] + GPIO_BANK_OFFSET, 1);
if (ret) {
printf("Unable to re-set loopback GPIO value\n");
return XRFDC_FAILURE;
}
}
}
return XRFDC_SUCCESS;
}
int txSend(convData_t* cmdArrgs) {
int ret;
/* Enable global start gpio */
ret = set_gpio(globalstart_gpio + GPIO_BANK_OFFSET, cmdArrgs[0].i);
if (ret) {
printf("Unable to enable globalstart GPIO value\n");
return XRFDC_FAILURE;
}
if(cmdArrgs[0].i) printf("Tx channel enabled\n");
else printf("Tx channel disabled\n");
return XRFDC_SUCCESS;
}
int writeDataSD(convData_t* cmdArrgs) {
int channels=cmdArrgs[0].i;
u32 size=0;
char path[128];
sprintf (path,"%s.txt", cmdArrgs[1].b);
size = read_from_file(path,(int16_t*)TX_BUFFER_BASE);
if(size<1){
printf("Error while reading the file\n");
return XST_FAILURE;
}
if (size > FIFO_SIZE) {
printf("size is too big\n");
return XST_FAILURE;
}
LoadFIFO(channels, size,(int16_t*)TX_BUFFER_BASE);
return 0;
}
int writeDataTCP(convData_t* cmdArrgs) {
int channels=cmdArrgs[0].i;
u32 nSamples=cmdArrgs[1].u;
if(nSamples%32){
printf("Error with alignment\n");
return XST_FAILURE;
}
if (nSamples*2 > FIFO_SIZE*16) {
printf("size is too big\n");
return XST_FAILURE;
}
if((readSamples((u8*)TX_BUFFER_BASE,nSamples*2))<0){
printf("Error while reading samples through TCP\n");
return XST_FAILURE;
}
LoadFIFO(channels, nSamples*2,(int16_t*)TX_BUFFER_BASE);
return 0;
}
| [
"[email protected]"
] | |
05c9a9f3ad7803bb613979c227bed2c47f5ea67f | 39a2afc9822cb25f115560de0388f6c0b3b14d71 | /src/mame/drivers/hanaroku.c | 56f9ea14ac92452e3b774d852d8e6bcd901660b3 | [] | no_license | Myprivateclonelibrary/historic-mess | 9726d1de085a46719cc154cac83ad2facbae6913 | d32490b1180bbeeeb6ee11c68fc9ab2523260640 | refs/heads/master | 2023-07-24T17:46:01.831563 | 2007-03-08T23:16:03 | 2007-03-08T23:16:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C | false | false | 9,567 | c | /* Hanaroku */
/*
TODO:
- colour decoding might not be perfect
- Background color should be green, but current handling might be wrong.
- some unknown sprite attributes, sprite flipping in flip screen needed
- don't know what to do when the jackpot is displayed (missing controls ?)
- according to the board pic, there should be one more 4-switches dip
switch bank, and probably some NVRAM because there's a battery.
*/
#include "driver.h"
#include "sound/ay8910.h"
/* video */
UINT8 *hanaroku_spriteram1;
UINT8 *hanaroku_spriteram2;
UINT8 *hanaroku_spriteram3;
PALETTE_INIT( hanaroku )
{
int i;
int r,g,b;
for (i = 0; i < 0x200; i++)
{
b = (color_prom[i*2+1] & 0x1f);
g = ((color_prom[i*2+1] & 0xe0) | ( (color_prom[i*2+0]& 0x03) <<8) ) >> 5;
r = (color_prom[i*2+0]&0x7c) >> 2;
palette_set_color(machine,i,pal5bit(r),pal5bit(g),pal5bit(b));
}
}
VIDEO_START(hanaroku)
{
return 0;
}
static void hanaroku_draw_sprites( mame_bitmap *bitmap, const rectangle *cliprect )
{
int i;
for (i = 511; i >= 0; i--)
{
int code = hanaroku_spriteram1[i] | (hanaroku_spriteram2[i] << 8);
int color = (hanaroku_spriteram2[i + 0x200] & 0xf8) >> 3;
int flipx = 0;
int flipy = 0;
int sx = hanaroku_spriteram1[i + 0x200] | ((hanaroku_spriteram2[i + 0x200] & 0x07) << 8);
int sy = 242 - hanaroku_spriteram3[i];
if (flip_screen)
{
sy = 242 - sy;
flipx = !flipx;
flipy = !flipy;
}
drawgfx(bitmap, Machine->gfx[0], code, color, flipx, flipy,
sx, sy, cliprect, TRANSPARENCY_PEN, 0);
}
}
VIDEO_UPDATE(hanaroku)
{
fillbitmap(bitmap, Machine->pens[0x1f0], cliprect); // ???
hanaroku_draw_sprites(bitmap, cliprect);
return 0;
}
static WRITE8_HANDLER( hanaroku_out_0_w )
{
/*
bit description
0 meter1 (coin1)
1 meter2 (coin2)
2 meter3 (1/2 d-up)
3 meter4
4 call out (meter)
5 lockout (key)
6 hopper2 (play)
7 meter5 (start)
*/
coin_counter_w(0, data & 0x01);
coin_counter_w(1, data & 0x02);
coin_counter_w(2, data & 0x04);
coin_counter_w(3, data & 0x08);
coin_counter_w(4, data & 0x80);
}
static WRITE8_HANDLER( hanaroku_out_1_w )
{
/*
bit description
0 hopper1 (data clear)
1 dis dat
2 dis clk
3 pay out
4 ext in 1
5 ext in 2
6 ?
7 ?
*/
}
static WRITE8_HANDLER( hanaroku_out_2_w )
{
// unused
}
/* main cpu */
static ADDRESS_MAP_START( readmem, ADDRESS_SPACE_PROGRAM, 8 )
AM_RANGE(0x0000, 0x7fff) AM_READ(MRA8_ROM)
AM_RANGE(0x8000, 0x87ff) AM_READ(MRA8_RAM)
AM_RANGE(0x9000, 0x97ff) AM_READ(MRA8_RAM)
AM_RANGE(0xa000, 0xa1ff) AM_READ(MRA8_RAM)
AM_RANGE(0xc000, 0xc3ff) AM_READ(MRA8_RAM)
AM_RANGE(0xc400, 0xc4ff) AM_READ(MRA8_RAM)
AM_RANGE(0xd000, 0xd000) AM_READ(AY8910_read_port_0_r)
AM_RANGE(0xe000, 0xe000) AM_READ(input_port_0_r)
AM_RANGE(0xe001, 0xe001) AM_READ(input_port_1_r)
AM_RANGE(0xe002, 0xe002) AM_READ(input_port_2_r)
AM_RANGE(0xe004, 0xe004) AM_READ(input_port_5_r)
ADDRESS_MAP_END
static ADDRESS_MAP_START( writemem, ADDRESS_SPACE_PROGRAM, 8 )
AM_RANGE(0x0000, 0x7fff) AM_WRITE(MWA8_ROM)
AM_RANGE(0x8000, 0x87ff) AM_WRITE(MWA8_RAM) AM_BASE(&hanaroku_spriteram1)
AM_RANGE(0x9000, 0x97ff) AM_WRITE(MWA8_RAM) AM_BASE(&hanaroku_spriteram2)
AM_RANGE(0xa000, 0xa1ff) AM_WRITE(MWA8_RAM) AM_BASE(&hanaroku_spriteram3)
AM_RANGE(0xa200, 0xa2ff) AM_WRITE(MWA8_NOP) // ??? written once during P.O.S.T.
AM_RANGE(0xa300, 0xa304) AM_WRITE(MWA8_NOP) // ???
AM_RANGE(0xc000, 0xc3ff) AM_WRITE(MWA8_RAM) // main ram
AM_RANGE(0xc400, 0xc4ff) AM_WRITE(MWA8_RAM) // ???
AM_RANGE(0xb000, 0xb000) AM_WRITE(MWA8_NOP) // ??? always 0x40
AM_RANGE(0xd000, 0xd000) AM_WRITE(AY8910_control_port_0_w)
AM_RANGE(0xd001, 0xd001) AM_WRITE(AY8910_write_port_0_w)
AM_RANGE(0xe000, 0xe000) AM_WRITE(hanaroku_out_0_w)
AM_RANGE(0xe002, 0xe002) AM_WRITE(hanaroku_out_1_w)
AM_RANGE(0xe004, 0xe004) AM_WRITE(hanaroku_out_2_w)
ADDRESS_MAP_END
INPUT_PORTS_START( hanaroku )
PORT_START_TAG("IN0") // IN0 (0xe000)
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_COIN1 ) // adds n credits depending on "Coinage" Dip Switch
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_COIN2 ) // adds 5 credits
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_SERVICE ) PORT_NAME("1/2 D-Up") PORT_CODE(KEYCODE_H)
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_SERVICE ) PORT_NAME("Reset") PORT_CODE(KEYCODE_R)
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_SERVICE ) PORT_NAME("Meter") PORT_CODE(KEYCODE_M)
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_SERVICE ) PORT_NAME("Key") PORT_CODE(KEYCODE_K)
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_START2 ) PORT_NAME("Play")
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_START1 ) PORT_NAME("Start")
PORT_START_TAG("IN1") // IN1 (0xe001)
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_NAME("Card 1")
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_BUTTON2 ) PORT_NAME("Card 2")
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_BUTTON3 ) PORT_NAME("Card 3")
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_BUTTON4 ) PORT_NAME("Card 4")
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_BUTTON5 ) PORT_NAME("Card 5")
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_BUTTON6 ) PORT_NAME("Card 6")
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_BUTTON7 ) PORT_NAME(DEF_STR( Yes )) PORT_CODE(KEYCODE_Y)
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_BUTTON8 ) PORT_NAME(DEF_STR( No )) PORT_CODE(KEYCODE_N)
PORT_START_TAG("IN2") // IN2 (0xe002)
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_SERVICE ) PORT_NAME("Data Clear") PORT_CODE(KEYCODE_D)
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_TILT )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_BUTTON9 ) PORT_NAME("Medal In") PORT_CODE(KEYCODE_I)
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_BUTTON10 ) PORT_NAME("Pay Out") PORT_CODE(KEYCODE_O)
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_SERVICE1 ) PORT_NAME("Ext In 1")
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_SERVICE2 ) PORT_NAME("Ext In 2")
PORT_BIT( 0xc0, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START_TAG("DSW1") // DSW1 (0xd000 - Port A)
PORT_BIT( 0xff, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START_TAG("DSW2") // DSW2 (0xd000 - Port B)
PORT_BIT( 0xff, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START_TAG("DSW3") // DSW3 (0xe004)
PORT_DIPNAME( 0x03, 0x03, DEF_STR( Coinage ) ) // Stored at 0xc028
PORT_DIPSETTING( 0x03, DEF_STR( 1C_1C ) )
PORT_DIPSETTING( 0x02, DEF_STR( 1C_2C ) )
PORT_DIPSETTING( 0x01, DEF_STR( 1C_5C ) )
PORT_DIPSETTING( 0x00, "1 Coin/10 Credits" )
PORT_DIPNAME( 0x04, 0x04, DEF_STR( Flip_Screen ) ) // Stored at 0xc03a
PORT_DIPSETTING( 0x04, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_DIPNAME( 0x08, 0x08, DEF_STR( Unknown ) ) // Stored at 0xc078
PORT_DIPSETTING( 0x08, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_DIPNAME( 0x30, 0x20, "Game Mode" ) // Stored at 0xc02e
PORT_DIPSETTING( 0x30, "Mode 0" ) // Collect OFF
PORT_DIPSETTING( 0x20, "Mode 1" ) // Collect ON (code at 0x36ea)
PORT_DIPSETTING( 0x10, "Mode 2" ) // Collect ON (code at 0x3728)
PORT_DIPSETTING( 0x00, "Mode 3" ) // No credit counter
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_SERVICE( 0x80, IP_ACTIVE_LOW )
INPUT_PORTS_END
static const gfx_layout hanaroku_charlayout =
{
16,16,
RGN_FRAC(1,4),
4,
{ RGN_FRAC(3,4),RGN_FRAC(2,4),RGN_FRAC(1,4),RGN_FRAC(0,4) },
{ 0,1,2,3,4,5,6,7,
64,65,66,67,68,69,70,71},
{ 0*8, 1*8, 2*8, 3*8, 4*8, 5*8, 6*8, 7*8,
128+0*8,128+1*8,128+2*8,128+3*8,128+4*8,128+5*8,128+6*8,128+7*8 },
16*16
};
static const gfx_decode gfxdecodeinfo[] =
{
{ REGION_GFX1, 0, &hanaroku_charlayout, 0, 32 },
{ -1 } /* end of array */
};
static struct AY8910interface ay8910_interface =
{
input_port_3_r,
input_port_4_r
};
static MACHINE_DRIVER_START( hanaroku )
MDRV_CPU_ADD(Z80,6000000) /* ? MHz */
MDRV_CPU_PROGRAM_MAP(readmem,writemem)
MDRV_CPU_VBLANK_INT(irq0_line_hold,1)
MDRV_SCREEN_REFRESH_RATE(60)
MDRV_SCREEN_VBLANK_TIME(DEFAULT_60HZ_VBLANK_DURATION)
/* video hardware */
MDRV_VIDEO_ATTRIBUTES(VIDEO_TYPE_RASTER )
MDRV_SCREEN_FORMAT(BITMAP_FORMAT_INDEXED16)
MDRV_SCREEN_SIZE(64*8, 64*8)
MDRV_SCREEN_VISIBLE_AREA(0, 48*8-1, 2*8, 30*8-1)
MDRV_GFXDECODE(gfxdecodeinfo)
MDRV_PALETTE_LENGTH(0x200)
MDRV_PALETTE_INIT(hanaroku)
MDRV_VIDEO_START(hanaroku)
MDRV_VIDEO_UPDATE(hanaroku)
/* sound hardware */
MDRV_SPEAKER_STANDARD_MONO("mono")
MDRV_SOUND_ADD(AY8910, 1500000)
MDRV_SOUND_CONFIG(ay8910_interface)
MDRV_SOUND_ROUTE(ALL_OUTPUTS, "mono", 0.50)
MACHINE_DRIVER_END
ROM_START( hanaroku )
ROM_REGION( 0x10000, REGION_CPU1, 0 ) /* z80 code */
ROM_LOAD( "zc5_1a.u02", 0x00000, 0x08000, CRC(9e3b62ce) SHA1(81aee570b67950c21ab3c8f9235dd383529b34d5) )
ROM_REGION( 0x20000, REGION_GFX1, 0 ) /* tiles */
ROM_LOAD( "zc0_002.u14", 0x00000, 0x08000, CRC(76adab7f) SHA1(6efbe52ae4a1d15fe93bd05058546bf146a64154) )
ROM_LOAD( "zc0_003.u15", 0x08000, 0x08000, CRC(c208e64b) SHA1(0bc226c39331bb2e1d4d8f756199ceec85c28f28) )
ROM_LOAD( "zc0_004.u16", 0x10000, 0x08000, CRC(e8a46ee4) SHA1(09cac230c1c49cb282f540b1608ad33b1cc1a943) )
ROM_LOAD( "zc0_005.u17", 0x18000, 0x08000, CRC(7ad160a5) SHA1(c897fbe4a7c2a2f352333131dfd1a76e176f0ed8) )
ROM_REGION( 0x0400, REGION_PROMS, 0 ) /* colour */
ROM_LOAD16_BYTE( "zc0_006.u21", 0x0000, 0x0200, CRC(8e8fbc30) SHA1(7075521bbd790c46c58d9e408b0d7d6a42ed00bc) )
ROM_LOAD16_BYTE( "zc0_007.u22", 0x0001, 0x0200, CRC(67225de1) SHA1(98322e71d93d247a67fb4e52edad6c6c32a603d8) )
ROM_END
GAME( 1988, hanaroku, 0, hanaroku, hanaroku, 0, ROT0, "Alba", "Hanaroku", GAME_NO_COCKTAIL | GAME_IMPERFECT_GRAPHICS | GAME_IMPERFECT_COLORS )
| [
"[email protected]"
] | |
fa10a0ae263efd9e2bcfddc5d100e485cb07e0b6 | 7df190df28da7e4ff166e55dc8ce780f11236a9f | /src/router/snmp/snmplib/snmp_api.c | 4725b16cfa1f8cd2fab09c64a9f3bf9fbc2b6af2 | [
"LicenseRef-scancode-other-permissive",
"BSD-3-Clause",
"MIT",
"MIT-CMU",
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | mirror/dd-wrt | 25416946e6132aa54b35809de61834a1825a9a36 | 8f2934a5a2adfbb59b471375aa3a38de5d036531 | refs/heads/master | 2023-08-31T14:54:47.496685 | 2023-08-30T17:40:54 | 2023-08-30T17:40:54 | 7,470,282 | 520 | 281 | null | 2023-05-29T20:56:24 | 2013-01-06T17:21:29 | null | WINDOWS-1252 | C | false | false | 258,970 | c |
/* Portions of this file are subject to the following copyright(s). See
* the Net-SNMP's COPYING file for more details and other copyrights
* that may apply:
*/
/******************************************************************
Copyright 1989, 1991, 1992 by Carnegie Mellon University
All Rights Reserved
Permission to use, copy, modify, and distribute this software and its
documentation for any purpose and without fee is hereby granted,
provided that the above copyright notice appear in all copies and that
both that copyright notice and this permission notice appear in
supporting documentation, and that the name of CMU not be
used in advertising or publicity pertaining to distribution of the
software without specific, written prior permission.
CMU DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL
CMU BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
SOFTWARE.
******************************************************************/
/*
* Portions of this file are copyrighted by:
* Copyright Copyright 2003 Sun Microsystems, Inc. All rights reserved.
* Use is subject to license terms specified in the COPYING file
* distributed with the Net-SNMP package.
*
* Portions of this file are copyrighted by:
* Copyright (c) 2016 VMware, Inc. All rights reserved.
* Use is subject to license terms specified in the COPYING file
* distributed with the Net-SNMP package.
*/
/** @defgroup library The Net-SNMP library
* @{
*/
/*
* snmp_api.c - API for access to snmp.
*/
#include <net-snmp/net-snmp-config.h>
#include <net-snmp/net-snmp-features.h>
#include <stdio.h>
#include <ctype.h>
#if HAVE_STDLIB_H
#include <stdlib.h>
#endif
#if HAVE_STRING_H
#include <string.h>
#else
#include <strings.h>
#endif
#if HAVE_UNISTD_H
#include <unistd.h>
#endif
#include <sys/types.h>
#if HAVE_SYS_PARAM_H
#include <sys/param.h>
#endif
#if TIME_WITH_SYS_TIME
# include <sys/time.h>
# include <time.h>
#else
# if HAVE_SYS_TIME_H
# include <sys/time.h>
# else
# include <time.h>
# endif
#endif
#ifdef HAVE_NETINET_IN_H
#include <netinet/in.h>
#endif
#ifdef HAVE_ARPA_INET_H
#include <arpa/inet.h>
#endif
#ifdef HAVE_SYS_SELECT_H
#include <sys/select.h>
#endif
#ifdef HAVE_IO_H
#include <io.h>
#endif
#ifdef HAVE_SYS_SOCKET_H
#include <sys/socket.h>
#endif
#ifdef HAVE_SYS_UN_H
#include <sys/un.h>
#endif
#ifdef HAVE_NETDB_H
#include <netdb.h>
#endif
#ifdef HAVE_NET_IF_DL_H
#ifndef dynix
#include <net/if_dl.h>
#else
#include <sys/net/if_dl.h>
#endif
#endif
#include <errno.h>
#if HAVE_LOCALE_H
#include <locale.h>
#endif
#define SNMP_NEED_REQUEST_LIST
#include <net-snmp/types.h>
#include <net-snmp/output_api.h>
#include <net-snmp/config_api.h>
#include <net-snmp/utilities.h>
#include <net-snmp/library/asn1.h>
#include <net-snmp/library/snmp.h> /* for xdump & {build,parse}_var_op */
#include <net-snmp/library/snmp_api.h>
#include <net-snmp/library/snmp_client.h>
#include <net-snmp/library/parse.h>
#include <net-snmp/library/mib.h>
#include <net-snmp/library/int64.h>
#include <net-snmp/library/snmpv3.h>
#include <net-snmp/library/callback.h>
#include <net-snmp/library/container.h>
#include <net-snmp/library/snmp_secmod.h>
#include <net-snmp/library/large_fd_set.h>
#ifdef NETSNMP_SECMOD_USM
#include <net-snmp/library/snmpusm.h>
#endif
#ifdef NETSNMP_SECMOD_KSM
#include <net-snmp/library/snmpksm.h>
#endif
#include <net-snmp/library/keytools.h>
#include <net-snmp/library/lcd_time.h>
#include <net-snmp/library/snmp_alarm.h>
#include <net-snmp/library/snmp_transport.h>
#include <net-snmp/library/snmp_service.h>
#include <net-snmp/library/vacm.h>
#if defined(NETSNMP_USE_OPENSSL) && defined(HAVE_LIBSSL)
#include <openssl/ssl.h>
#include <net-snmp/library/cert_util.h>
#endif
netsnmp_feature_child_of(statistics, libnetsnmp);
netsnmp_feature_child_of(snmp_api, libnetsnmp);
netsnmp_feature_child_of(oid_is_subtree, snmp_api);
netsnmp_feature_child_of(snmpv3_probe_contextEngineID_rfc5343, snmp_api);
static void _init_snmp(void);
static int _snmp_store_needed = 0;
#include "../agent/mibgroup/agentx/protocol.h"
#include <net-snmp/library/transform_oids.h>
#ifndef timercmp
#define timercmp(tvp, uvp, cmp) \
/* CSTYLED */ \
((tvp)->tv_sec cmp (uvp)->tv_sec || \
((tvp)->tv_sec == (uvp)->tv_sec && \
/* CSTYLED */ \
(tvp)->tv_usec cmp (uvp)->tv_usec))
#endif
#ifndef timerclear
#define timerclear(tvp) (tvp)->tv_sec = (tvp)->tv_usec = 0
#endif
/*
* Globals.
*/
#ifndef NETSNMP_STREAM_QUEUE_LEN
#define NETSNMP_STREAM_QUEUE_LEN 5
#endif
#ifndef BSD4_3
#define BSD4_2
#endif
static oid default_enterprise[] = { 1, 3, 6, 1, 4, 1, 3, 1, 1 };
/*
* enterprises.cmu.systems.cmuSNMP
*/
#define DEFAULT_COMMUNITY "public"
#define DEFAULT_RETRIES 5
#define DEFAULT_TIMEOUT ONE_SEC
#define DEFAULT_REMPORT SNMP_PORT
#define DEFAULT_ENTERPRISE default_enterprise
#define DEFAULT_TIME 0
/*
* Internal information about the state of the snmp session.
*/
struct snmp_internal_session {
netsnmp_request_list *requests; /* Info about outstanding requests */
netsnmp_request_list *requestsEnd; /* ptr to end of list */
int (*hook_pre) (netsnmp_session *, netsnmp_transport *,
void *, int);
int (*hook_parse) (netsnmp_session *, netsnmp_pdu *,
u_char *, size_t);
int (*hook_post) (netsnmp_session *, netsnmp_pdu *, int);
int (*hook_build) (netsnmp_session *, netsnmp_pdu *,
u_char *, size_t *);
int (*hook_realloc_build) (netsnmp_session *,
netsnmp_pdu *, u_char **,
size_t *, size_t *);
int (*check_packet) (u_char *, size_t);
netsnmp_pdu *(*hook_create_pdu) (netsnmp_transport *,
void *, size_t);
u_char *packet; /* curr rcv packet data (may be incomplete) */
size_t packet_len; /* length of data received so far */
size_t packet_size; /* size of buffer for packet data */
u_char *obuf; /* send packet buffer */
size_t obuf_size; /* size of buffer for packet data */
u_char *opacket; /* send packet data (within obuf) */
size_t opacket_len; /* length of data */
};
/*
* information about received packet
*/
typedef struct snmp_rcv_packet_s {
u_char *packet;
size_t packet_len;
void *opaque;
int olength;
} snmp_rcv_packet;
static const char *api_errors[-SNMPERR_MAX + 1] = {
"No error", /* SNMPERR_SUCCESS */
"Generic error", /* SNMPERR_GENERR */
"Invalid local port", /* SNMPERR_BAD_LOCPORT */
"Unknown host", /* SNMPERR_BAD_ADDRESS */
"Unknown session", /* SNMPERR_BAD_SESSION */
"Too long", /* SNMPERR_TOO_LONG */
"No socket", /* SNMPERR_NO_SOCKET */
"Cannot send V2 PDU on V1 session", /* SNMPERR_V2_IN_V1 */
"Cannot send V1 PDU on V2 session", /* SNMPERR_V1_IN_V2 */
"Bad value for non-repeaters", /* SNMPERR_BAD_REPEATERS */
"Bad value for max-repetitions", /* SNMPERR_BAD_REPETITIONS */
"Error building ASN.1 representation", /* SNMPERR_BAD_ASN1_BUILD */
"Failure in sendto", /* SNMPERR_BAD_SENDTO */
"Bad parse of ASN.1 type", /* SNMPERR_BAD_PARSE */
"Bad version specified", /* SNMPERR_BAD_VERSION */
"Bad source party specified", /* SNMPERR_BAD_SRC_PARTY */
"Bad destination party specified", /* SNMPERR_BAD_DST_PARTY */
"Bad context specified", /* SNMPERR_BAD_CONTEXT */
"Bad community specified", /* SNMPERR_BAD_COMMUNITY */
"Cannot send noAuth/Priv", /* SNMPERR_NOAUTH_DESPRIV */
"Bad ACL definition", /* SNMPERR_BAD_ACL */
"Bad Party definition", /* SNMPERR_BAD_PARTY */
"Session abort failure", /* SNMPERR_ABORT */
"Unknown PDU type", /* SNMPERR_UNKNOWN_PDU */
"Timeout", /* SNMPERR_TIMEOUT */
"Failure in recvfrom", /* SNMPERR_BAD_RECVFROM */
"Unable to determine contextEngineID", /* SNMPERR_BAD_ENG_ID */
"No securityName specified", /* SNMPERR_BAD_SEC_NAME */
"Unable to determine securityLevel", /* SNMPERR_BAD_SEC_LEVEL */
"ASN.1 parse error in message", /* SNMPERR_ASN_PARSE_ERR */
"Unknown security model in message", /* SNMPERR_UNKNOWN_SEC_MODEL */
"Invalid message (e.g. msgFlags)", /* SNMPERR_INVALID_MSG */
"Unknown engine ID", /* SNMPERR_UNKNOWN_ENG_ID */
"Unknown user name", /* SNMPERR_UNKNOWN_USER_NAME */
"Unsupported security level", /* SNMPERR_UNSUPPORTED_SEC_LEVEL */
"Authentication failure (incorrect password, community or key)", /* SNMPERR_AUTHENTICATION_FAILURE */
"Not in time window", /* SNMPERR_NOT_IN_TIME_WINDOW */
"Decryption error", /* SNMPERR_DECRYPTION_ERR */
"SCAPI general failure", /* SNMPERR_SC_GENERAL_FAILURE */
"SCAPI sub-system not configured", /* SNMPERR_SC_NOT_CONFIGURED */
"Key tools not available", /* SNMPERR_KT_NOT_AVAILABLE */
"Unknown Report message", /* SNMPERR_UNKNOWN_REPORT */
"USM generic error", /* SNMPERR_USM_GENERICERROR */
"USM unknown security name (no such user exists)", /* SNMPERR_USM_UNKNOWNSECURITYNAME */
"USM unsupported security level (this user has not been configured for that level of security)", /* SNMPERR_USM_UNSUPPORTEDSECURITYLEVEL */
"USM encryption error", /* SNMPERR_USM_ENCRYPTIONERROR */
"USM authentication failure (incorrect password or key)", /* SNMPERR_USM_AUTHENTICATIONFAILURE */
"USM parse error", /* SNMPERR_USM_PARSEERROR */
"USM unknown engineID", /* SNMPERR_USM_UNKNOWNENGINEID */
"USM not in time window", /* SNMPERR_USM_NOTINTIMEWINDOW */
"USM decryption error", /* SNMPERR_USM_DECRYPTIONERROR */
"MIB not initialized", /* SNMPERR_NOMIB */
"Value out of range", /* SNMPERR_RANGE */
"Sub-id out of range", /* SNMPERR_MAX_SUBID */
"Bad sub-id in object identifier", /* SNMPERR_BAD_SUBID */
"Object identifier too long", /* SNMPERR_LONG_OID */
"Bad value name", /* SNMPERR_BAD_NAME */
"Bad value notation", /* SNMPERR_VALUE */
"Unknown Object Identifier", /* SNMPERR_UNKNOWN_OBJID */
"No PDU in snmp_send", /* SNMPERR_NULL_PDU */
"Missing variables in PDU", /* SNMPERR_NO_VARS */
"Bad variable type", /* SNMPERR_VAR_TYPE */
"Out of memory (malloc failure)", /* SNMPERR_MALLOC */
"Kerberos related error", /* SNMPERR_KRB5 */
"Protocol error", /* SNMPERR_PROTOCOL */
"OID not increasing", /* SNMPERR_OID_NONINCREASING */
"Context probe", /* SNMPERR_JUST_A_CONTEXT_PROBE */
"Configuration data found but the transport can't be configured", /* SNMPERR_TRANSPORT_NO_CONFIG */
"Transport configuration failed", /* SNMPERR_TRANSPORT_CONFIG_ERROR */
};
static const char *secLevelName[] = {
"BAD_SEC_LEVEL",
"noAuthNoPriv",
"authNoPriv",
"authPriv"
};
/*
* Multiple threads may changes these variables.
* Suggest using the Single API, which does not use Sessions.
*
* Reqid may need to be protected. Time will tell...
*
*/
/*
* MTCRITICAL_RESOURCE
*/
/*
* use token in comments to individually protect these resources
*/
struct session_list *Sessions = NULL; /* MT_LIB_SESSION */
static long Reqid = 0; /* MT_LIB_REQUESTID */
static long Msgid = 0; /* MT_LIB_MESSAGEID */
static long Sessid = 0; /* MT_LIB_SESSIONID */
static long Transid = 0; /* MT_LIB_TRANSID */
int snmp_errno = 0;
/*
* END MTCRITICAL_RESOURCE
*/
/*
* global error detail storage
*/
static char snmp_detail[192];
static int snmp_detail_f = 0;
/*
* Prototypes.
*/
static void snmpv3_calc_msg_flags(int, int, u_char *);
static int snmpv3_verify_msg(netsnmp_request_list *, netsnmp_pdu *);
static int snmpv3_build(u_char ** pkt, size_t * pkt_len,
size_t * offset, netsnmp_session * session,
netsnmp_pdu *pdu);
static int snmp_parse_version(u_char *, size_t);
static int snmp_resend_request(struct session_list *slp,
netsnmp_request_list *orp,
netsnmp_request_list *rp,
int incr_retries);
static void register_default_handlers(void);
static struct session_list *snmp_sess_copy(netsnmp_session * pss);
/*
* return configured max message size for outgoing packets
*/
int
netsnmp_max_send_msg_size(void)
{
u_int max = netsnmp_ds_get_int(NETSNMP_DS_LIBRARY_ID,
NETSNMP_DS_LIB_MSG_SEND_MAX);
if (0 == max)
max = SNMP_MAX_PACKET_LEN;
else if (max < SNMP_MIN_MAX_LEN)
max = SNMP_MIN_MAX_LEN; /* minimum max size per SNMP specs */
else if (max > SNMP_MAX_PACKET_LEN)
max = SNMP_MAX_PACKET_LEN;
return max;
}
#ifndef HAVE_STRERROR
const char *
strerror(int err)
{
extern const char *sys_errlist[];
extern int sys_nerr;
if (err < 0 || err >= sys_nerr)
return "Unknown error";
return sys_errlist[err];
}
#endif
const char *
snmp_pdu_type(int type)
{
static char unknown[20];
switch(type) {
case SNMP_MSG_GET:
return "GET";
case SNMP_MSG_GETNEXT:
return "GETNEXT";
case SNMP_MSG_GETBULK:
return "GETBULK";
#ifndef NETSNMP_NO_WRITE_SUPPORT
case SNMP_MSG_SET:
return "SET";
#endif /* !NETSNMP_NO_WRITE_SUPPORT */
case SNMP_MSG_RESPONSE:
return "RESPONSE";
case SNMP_MSG_TRAP:
return "TRAP";
case SNMP_MSG_INFORM:
return "INFORM";
case SNMP_MSG_TRAP2:
return "TRAP2";
case SNMP_MSG_REPORT:
return "REPORT";
default:
snprintf(unknown, sizeof(unknown), "?0x%2X?", type);
return unknown;
}
}
#define DEBUGPRINTPDUTYPE(token, type) \
DEBUGDUMPSECTION(token, snmp_pdu_type(type))
long
snmp_get_next_reqid(void)
{
long retVal;
snmp_res_lock(MT_LIBRARY_ID, MT_LIB_REQUESTID);
retVal = 1 + Reqid; /*MTCRITICAL_RESOURCE */
if (!retVal)
retVal = 2;
Reqid = retVal;
if (netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_16BIT_IDS))
retVal &= 0x7fff; /* mask to 15 bits */
else
retVal &= 0x7fffffff; /* mask to 31 bits */
if (!retVal) {
Reqid = retVal = 2;
}
snmp_res_unlock(MT_LIBRARY_ID, MT_LIB_REQUESTID);
return retVal;
}
long
snmp_get_next_msgid(void)
{
long retVal;
snmp_res_lock(MT_LIBRARY_ID, MT_LIB_MESSAGEID);
retVal = 1 + Msgid; /*MTCRITICAL_RESOURCE */
if (!retVal)
retVal = 2;
Msgid = retVal;
if (netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_16BIT_IDS))
retVal &= 0x7fff; /* mask to 15 bits */
else
retVal &= 0x7fffffff; /* mask to 31 bits */
if (!retVal) {
Msgid = retVal = 2;
}
snmp_res_unlock(MT_LIBRARY_ID, MT_LIB_MESSAGEID);
return retVal;
}
long
snmp_get_next_sessid(void)
{
long retVal;
snmp_res_lock(MT_LIBRARY_ID, MT_LIB_SESSIONID);
retVal = 1 + Sessid; /*MTCRITICAL_RESOURCE */
if (!retVal)
retVal = 2;
Sessid = retVal;
if (netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_16BIT_IDS))
retVal &= 0x7fff; /* mask to 15 bits */
else
retVal &= 0x7fffffff; /* mask to 31 bits */
if (!retVal) {
Sessid = retVal = 2;
}
snmp_res_unlock(MT_LIBRARY_ID, MT_LIB_SESSIONID);
return retVal;
}
long
snmp_get_next_transid(void)
{
long retVal;
snmp_res_lock(MT_LIBRARY_ID, MT_LIB_TRANSID);
retVal = 1 + Transid; /*MTCRITICAL_RESOURCE */
if (!retVal)
retVal = 2;
Transid = retVal;
if (netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_16BIT_IDS))
retVal &= 0x7fff; /* mask to 15 bits */
else
retVal &= 0x7fffffff; /* mask to 31 bits */
if (!retVal) {
Transid = retVal = 2;
}
snmp_res_unlock(MT_LIBRARY_ID, MT_LIB_TRANSID);
return retVal;
}
void
snmp_perror(const char *prog_string)
{
const char *str;
int xerr;
xerr = snmp_errno; /*MTCRITICAL_RESOURCE */
str = snmp_api_errstring(xerr);
snmp_log(LOG_ERR, "%s: %s\n", prog_string, str);
}
void
snmp_set_detail(const char *detail_string)
{
if (detail_string != NULL) {
strlcpy((char *) snmp_detail, detail_string, sizeof(snmp_detail));
snmp_detail_f = 1;
}
}
/*
* returns pointer to static data
*/
/*
* results not guaranteed in multi-threaded use
*/
const char *
snmp_api_errstring(int snmp_errnumber)
{
const char *msg = "";
static char msg_buf[SPRINT_MAX_LEN];
if (snmp_errnumber >= SNMPERR_MAX && snmp_errnumber <= SNMPERR_GENERR) {
msg = api_errors[-snmp_errnumber];
} else if (snmp_errnumber != SNMPERR_SUCCESS) {
msg = NULL;
}
if (!msg) {
snprintf(msg_buf, sizeof(msg_buf), "Unknown error: %d", snmp_errnumber);
msg_buf[sizeof(msg_buf)-1] = '\0';
} else if (snmp_detail_f) {
snprintf(msg_buf, sizeof(msg_buf), "%s (%s)", msg, snmp_detail);
msg_buf[sizeof(msg_buf)-1] = '\0';
snmp_detail_f = 0;
} else {
strlcpy(msg_buf, msg, sizeof(msg_buf));
}
return (msg_buf);
}
/*
* snmp_error - return error data
* Inputs : address of errno, address of snmp_errno, address of string
* Caller must free the string returned after use.
*/
void
snmp_error(netsnmp_session * psess,
int *p_errno, int *p_snmp_errno, char **p_str)
{
char buf[SPRINT_MAX_LEN];
int snmp_errnumber;
if (p_errno)
*p_errno = psess->s_errno;
if (p_snmp_errno)
*p_snmp_errno = psess->s_snmp_errno;
if (p_str == NULL)
return;
strcpy(buf, "");
snmp_errnumber = psess->s_snmp_errno;
if (snmp_errnumber >= SNMPERR_MAX && snmp_errnumber <= SNMPERR_GENERR) {
if (snmp_detail_f) {
snprintf(buf, sizeof(buf), "%s (%s)", api_errors[-snmp_errnumber],
snmp_detail);
buf[sizeof(buf)-1] = '\0';
snmp_detail_f = 0;
}
else
strlcpy(buf, api_errors[-snmp_errnumber], sizeof(buf));
} else {
if (snmp_errnumber) {
snprintf(buf, sizeof(buf), "Unknown Error %d", snmp_errnumber);
buf[sizeof(buf)-1] = '\0';
}
}
/*
* append a useful system errno interpretation.
*/
if (psess->s_errno) {
const char* error = strerror(psess->s_errno);
if(error == NULL)
error = "Unknown Error";
snprintf (&buf[strlen(buf)], sizeof(buf)-strlen(buf),
" (%s)", error);
}
buf[sizeof(buf)-1] = '\0';
*p_str = strdup(buf);
}
/*
* snmp_sess_error - same as snmp_error for single session API use.
*/
void
snmp_sess_error(void *sessp, int *p_errno, int *p_snmp_errno, char **p_str)
{
struct session_list *slp = (struct session_list *) sessp;
if ((slp) && (slp->session))
snmp_error(slp->session, p_errno, p_snmp_errno, p_str);
}
/*
* netsnmp_sess_log_error(): print a error stored in a session pointer
*/
void
netsnmp_sess_log_error(int priority,
const char *prog_string, netsnmp_session * ss)
{
char *err;
snmp_error(ss, NULL, NULL, &err);
snmp_log(priority, "%s: %s\n", prog_string, err);
SNMP_FREE(err);
}
/*
* snmp_sess_perror(): print a error stored in a session pointer
*/
void
snmp_sess_perror(const char *prog_string, netsnmp_session * ss)
{
netsnmp_sess_log_error(LOG_ERR, prog_string, ss);
}
long int netsnmp_random(void)
{
#if defined(HAVE_RANDOM)
/*
* The function random() is a more sophisticated random number generator
* which uses nonlinear feedback and an internal table that is 124 bytes
* (992 bits) long. The function returns random values that are 32 bits in
* length. All of the bits generated by random() are usable. The random()
* function is adequate for simulations and games, but should not be used
* for security related applications such as picking cryptographic keys or
* simulating one-time pads.
*/
return random();
#elif defined(HAVE_LRAND48)
/*
* As with random(), lrand48() provides excellent random numbers for
* simulations and games, but should not be used for security-related
* applications such as picking cryptographic keys or simulating one-time
* pads; linear congruential algorithms are too easy to break.
*/
return lrand48();
#elif defined(HAVE_RAND)
/*
* The original UNIX random number generator, rand(), is not a very good
* random number generator. It uses a 32-bit seed and maintains a 32-bit
* internal state.
*/
return rand();
#else
#error "Neither random(), nor lrand48() nor rand() are available"
#endif
}
void netsnmp_srandom(unsigned int seed)
{
#if defined(HAVE_SRANDOM)
srandom(seed);
#elif defined(HAVE_SRAND48)
srand48(seed);
#elif defined(HAVE_SRAND)
srand(seed);
#else
#error "Neither srandom(), nor srand48() nor srand() are available"
#endif
}
/*
* Primordial SNMP library initialization.
* Initializes mutex locks.
* Invokes minimum required initialization for displaying MIB objects.
* Gets initial request ID for all transactions,
* and finds which port SNMP over UDP uses.
* SNMP over AppleTalk is not currently supported.
*
* Warning: no debug messages here.
*/
static char _init_snmp_init_done = 0;
static void
_init_snmp(void)
{
struct timeval tv;
long tmpReqid, tmpMsgid;
if (_init_snmp_init_done)
return;
_init_snmp_init_done = 1;
Reqid = 1;
snmp_res_init(); /* initialize the mt locking structures */
#ifndef NETSNMP_DISABLE_MIB_LOADING
netsnmp_init_mib_internals();
#endif /* NETSNMP_DISABLE_MIB_LOADING */
netsnmp_tdomain_init();
gettimeofday(&tv, (struct timezone *) 0);
/*
* Now = tv;
*/
/*
* get pseudo-random values for request ID and message ID
*/
netsnmp_srandom((unsigned)(tv.tv_sec ^ tv.tv_usec));
tmpReqid = netsnmp_random();
tmpMsgid = netsnmp_random();
/*
* don't allow zero value to repeat init
*/
if (tmpReqid == 0)
tmpReqid = 1;
if (tmpMsgid == 0)
tmpMsgid = 1;
Reqid = tmpReqid;
Msgid = tmpMsgid;
netsnmp_register_default_domain("snmp", "udp udp6");
netsnmp_register_default_domain("snmptrap", "udp udp6");
netsnmp_register_default_target("snmp", "udp", ":161");
netsnmp_register_default_target("snmp", "tcp", ":161");
netsnmp_register_default_target("snmp", "udp6", ":161");
netsnmp_register_default_target("snmp", "tcp6", ":161");
netsnmp_register_default_target("snmp", "dtlsudp", ":10161");
netsnmp_register_default_target("snmp", "tlstcp", ":10161");
netsnmp_register_default_target("snmp", "ipx", "/36879");
netsnmp_register_default_target("snmptrap", "udp", ":162");
netsnmp_register_default_target("snmptrap", "tcp", ":162");
netsnmp_register_default_target("snmptrap", "udp6", ":162");
netsnmp_register_default_target("snmptrap", "tcp6", ":162");
netsnmp_register_default_target("snmptrap", "dtlsudp", ":10162");
netsnmp_register_default_target("snmptrap", "tlstcp", ":10162");
netsnmp_register_default_target("snmptrap", "ipx", "/36880");
netsnmp_ds_set_int(NETSNMP_DS_LIBRARY_ID,
NETSNMP_DS_LIB_HEX_OUTPUT_LENGTH, 16);
netsnmp_ds_set_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_RETRIES,
DEFAULT_RETRIES);
netsnmp_ds_set_boolean(NETSNMP_DS_LIBRARY_ID,
NETSNMP_DS_LIB_MIB_ERRORS, 1);
#ifdef NETSNMP_USE_REVERSE_ASNENCODING
netsnmp_ds_set_boolean(NETSNMP_DS_LIBRARY_ID,
NETSNMP_DS_LIB_REVERSE_ENCODE,
NETSNMP_DEFAULT_ASNENCODING_DIRECTION);
#endif
}
/*
* Initializes the session structure.
* May perform one time minimal library initialization.
* No MIB file processing is done via this call.
*/
void
snmp_sess_init(netsnmp_session * session)
{
_init_snmp();
/*
* initialize session to default values
*/
memset(session, 0, sizeof(netsnmp_session));
session->timeout = SNMP_DEFAULT_TIMEOUT;
session->retries = SNMP_DEFAULT_RETRIES;
session->version = SNMP_DEFAULT_VERSION;
session->securityModel = SNMP_DEFAULT_SECMODEL;
session->rcvMsgMaxSize = netsnmp_max_send_msg_size();
session->sndMsgMaxSize = netsnmp_max_send_msg_size();
session->flags |= SNMP_FLAGS_DONT_PROBE;
}
static void
register_default_handlers(void)
{
netsnmp_ds_register_config(ASN_BOOLEAN, "snmp", "dumpPacket",
NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_DUMP_PACKET);
netsnmp_ds_register_config(ASN_BOOLEAN, "snmp", "reverseEncodeBER",
NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_REVERSE_ENCODE);
netsnmp_ds_register_config(ASN_INTEGER, "snmp", "defaultPort",
NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_DEFAULT_PORT);
#ifndef NETSNMP_FEATURE_REMOVE_RUNTIME_DISABLE_VERSION
netsnmp_ds_register_config(ASN_BOOLEAN, "snmp", "disableSNMPv3",
NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_DISABLE_V3);
#endif /* NETSNMP_FEATURE_REMOVE_RUNTIME_DISABLE_VERSION */
#if !defined(NETSNMP_DISABLE_SNMPV1) || !defined(NETSNMP_DISABLE_SNMPV2C)
#ifndef NETSNMP_FEATURE_REMOVE_RUNTIME_DISABLE_VERSION
#if !defined(NETSNMP_DISABLE_SNMPV1)
netsnmp_ds_register_config(ASN_BOOLEAN, "snmp", "disableSNMPv1",
NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_DISABLE_V1);
#endif
#if !defined(NETSNMP_DISABLE_SNMPV2C)
netsnmp_ds_register_config(ASN_BOOLEAN, "snmp", "disableSNMPv2c",
NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_DISABLE_V2c);
#endif
#endif /* NETSNMP_FEATURE_REMOVE_RUNTIME_DISABLE_VERSION */
netsnmp_ds_register_config(ASN_OCTET_STR, "snmp", "defCommunity",
NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_COMMUNITY);
#endif /* !defined(NETSNMP_DISABLE_SNMPV1) || !defined(NETSNMP_DISABLE_SNMPV2C) */
netsnmp_ds_register_premib(ASN_BOOLEAN, "snmp", "noTokenWarnings",
NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_NO_TOKEN_WARNINGS);
netsnmp_ds_register_config(ASN_BOOLEAN, "snmp", "noRangeCheck",
NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_DONT_CHECK_RANGE);
netsnmp_ds_register_premib(ASN_OCTET_STR, "snmp", "persistentDir",
NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_PERSISTENT_DIR);
netsnmp_ds_register_config(ASN_OCTET_STR, "snmp", "tempFilePattern",
NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_TEMP_FILE_PATTERN);
netsnmp_ds_register_config(ASN_BOOLEAN, "snmp", "noDisplayHint",
NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_NO_DISPLAY_HINT);
netsnmp_ds_register_config(ASN_BOOLEAN, "snmp", "16bitIDs",
NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_16BIT_IDS);
netsnmp_ds_register_premib(ASN_OCTET_STR, "snmp", "clientaddr",
NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_CLIENT_ADDR);
netsnmp_ds_register_premib(ASN_BOOLEAN, "snmp", "clientaddrUsesPort",
NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_CLIENT_ADDR_USES_PORT);
netsnmp_ds_register_config(ASN_INTEGER, "snmp", "serverSendBuf",
NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_SERVERSENDBUF);
netsnmp_ds_register_config(ASN_INTEGER, "snmp", "serverRecvBuf",
NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_SERVERRECVBUF);
netsnmp_ds_register_config(ASN_INTEGER, "snmp", "clientSendBuf",
NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_CLIENTSENDBUF);
netsnmp_ds_register_config(ASN_INTEGER, "snmp", "clientRecvBuf",
NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_CLIENTRECVBUF);
netsnmp_ds_register_config(ASN_INTEGER, "snmp", "sendMessageMaxSize",
NETSNMP_DS_LIBRARY_ID,
NETSNMP_DS_LIB_MSG_SEND_MAX);
netsnmp_ds_register_config(ASN_BOOLEAN, "snmp", "noPersistentLoad",
NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_DISABLE_PERSISTENT_LOAD);
netsnmp_ds_register_config(ASN_BOOLEAN, "snmp", "noPersistentSave",
NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_DISABLE_PERSISTENT_SAVE);
netsnmp_ds_register_config(ASN_BOOLEAN, "snmp",
"noContextEngineIDDiscovery",
NETSNMP_DS_LIBRARY_ID,
NETSNMP_DS_LIB_NO_DISCOVERY);
netsnmp_ds_register_config(ASN_INTEGER, "snmp", "timeout",
NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_TIMEOUT);
netsnmp_ds_register_config(ASN_INTEGER, "snmp", "retries",
NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_RETRIES);
netsnmp_ds_register_config(ASN_OCTET_STR, "snmp", "outputPrecision",
NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_OUTPUT_PRECISION);
netsnmp_register_service_handlers();
}
static int init_snmp_init_done = 0; /* To prevent double init's. */
/**
* Calls the functions to do config file loading and mib module parsing
* in the correct order.
*
* @param type label for the config file "type"
*
* @return void
*
* @see init_agent
*/
void
init_snmp(const char *type)
{
if (init_snmp_init_done) {
return;
}
init_snmp_init_done = 1;
/*
* make the type available everywhere else
*/
if (type && !netsnmp_ds_get_string(NETSNMP_DS_LIBRARY_ID,
NETSNMP_DS_LIB_APPTYPE)) {
netsnmp_ds_set_string(NETSNMP_DS_LIBRARY_ID,
NETSNMP_DS_LIB_APPTYPE, type);
}
_init_snmp();
/*
* set our current locale properly to initialize isprint() type functions
*/
#ifdef HAVE_SETLOCALE
setlocale(LC_CTYPE, "");
#endif
snmp_debug_init(); /* should be done first, to turn on debugging ASAP */
netsnmp_container_init_list();
init_callbacks();
init_snmp_logging();
snmp_init_statistics();
register_mib_handlers();
register_default_handlers();
init_snmp_transport();
init_snmpv3(type);
init_snmp_alarm();
init_snmp_enum(type);
init_vacm();
#if defined(NETSNMP_USE_OPENSSL) && defined(HAVE_LIBSSL) && NETSNMP_TRANSPORT_TLSBASE_DOMAIN
netsnmp_certs_init();
#endif
#ifdef DNSSEC_LOCAL_VALIDATION
netsnmp_ds_register_config(ASN_BOOLEAN, "snmp", "dnssecWarnOnly",
NETSNMP_DS_LIBRARY_ID,
NETSNMP_DS_LIB_DNSSEC_WARN_ONLY);
#endif
read_premib_configs();
#ifndef NETSNMP_DISABLE_MIB_LOADING
netsnmp_init_mib();
#endif /* NETSNMP_DISABLE_MIB_LOADING */
read_configs();
} /* end init_snmp() */
/**
* set a flag indicating that the persistent store needs to be saved.
*/
void
snmp_store_needed(const char *type)
{
DEBUGMSGTL(("snmp_store", "setting needed flag...\n"));
_snmp_store_needed = 1;
}
void
snmp_store_if_needed(void)
{
if (0 == _snmp_store_needed)
return;
DEBUGMSGTL(("snmp_store", "store needed...\n"));
snmp_store(netsnmp_ds_get_string(NETSNMP_DS_LIBRARY_ID,
NETSNMP_DS_LIB_APPTYPE));
_snmp_store_needed = 0;
}
void
snmp_store(const char *type)
{
DEBUGMSGTL(("snmp_store", "storing stuff...\n"));
snmp_save_persistent(type);
snmp_call_callbacks(SNMP_CALLBACK_LIBRARY, SNMP_CALLBACK_STORE_DATA, NULL);
snmp_clean_persistent(type);
}
/**
* Shuts down the application, saving any needed persistent storage,
* and appropriate clean up.
*
* @param type Label for the config file "type" used
*
* @return void
*/
void
snmp_shutdown(const char *type)
{
snmp_store(type);
snmp_call_callbacks(SNMP_CALLBACK_LIBRARY, SNMP_CALLBACK_SHUTDOWN, NULL);
shutdown_snmp_logging();
snmp_alarm_unregister_all();
snmp_close_sessions();
#ifndef NETSNMP_DISABLE_MIB_LOADING
shutdown_mib();
#endif /* NETSNMP_DISABLE_MIB_LOADING */
#if defined(NETSNMP_USE_OPENSSL) && defined(HAVE_LIBSSL) && NETSNMP_TRANSPORT_TLSBASE_DOMAIN
netsnmp_certs_shutdown();
#endif
#if !defined(NETSNMP_FEATURE_REMOVE_FILTER_SOURCE)
netsnmp_transport_filter_cleanup();
#endif
unregister_all_config_handlers();
netsnmp_container_free_list();
clear_sec_mod();
clear_snmp_enum();
netsnmp_clear_tdomain_list();
clear_callback();
netsnmp_ds_shutdown();
netsnmp_clear_default_target();
netsnmp_clear_default_domain();
shutdown_secmod();
shutdown_snmp_transport();
shutdown_data_list();
snmp_debug_shutdown(); /* should be done last */
init_snmp_init_done = 0;
_init_snmp_init_done = 0;
}
/*
* inserts session into session list
*/
void snmp_session_insert(struct session_list *slp)
{
if (NULL == slp)
return;
snmp_res_lock(MT_LIBRARY_ID, MT_LIB_SESSION);
slp->next = Sessions;
Sessions = slp;
snmp_res_unlock(MT_LIBRARY_ID, MT_LIB_SESSION);
}
/*
* Sets up the session with the snmp_session information provided by the user.
* Then opens and binds the necessary low-level transport. A handle to the
* created session is returned (this is NOT the same as the pointer passed to
* snmp_open()). On any error, NULL is returned and snmp_errno is set to the
* appropriate error code.
*/
netsnmp_session *
snmp_open(netsnmp_session *session)
{
struct session_list *slp;
slp = (struct session_list *) snmp_sess_open(session);
if (!slp) {
return NULL;
}
snmp_session_insert(slp);
return (slp->session);
}
/*
* extended open
*/
netsnmp_feature_child_of(snmp_open_ex, netsnmp_unused);
#ifndef NETSNMP_FEATURE_REMOVE_SNMP_OPEN_EX
netsnmp_session *
snmp_open_ex(netsnmp_session *session,
int (*fpre_parse) (netsnmp_session *, netsnmp_transport *,
void *, int),
int (*fparse) (netsnmp_session *, netsnmp_pdu *, u_char *,
size_t),
int (*fpost_parse) (netsnmp_session *, netsnmp_pdu *, int),
int (*fbuild) (netsnmp_session *, netsnmp_pdu *, u_char *,
size_t *),
int (*frbuild) (netsnmp_session *, netsnmp_pdu *,
u_char **, size_t *, size_t *),
int (*fcheck) (u_char *, size_t)
)
{
struct session_list *slp;
slp = (struct session_list *) snmp_sess_open(session);
if (!slp) {
return NULL;
}
slp->internal->hook_pre = fpre_parse;
slp->internal->hook_parse = fparse;
slp->internal->hook_post = fpost_parse;
slp->internal->hook_build = fbuild;
slp->internal->hook_realloc_build = frbuild;
slp->internal->check_packet = fcheck;
snmp_session_insert(slp);
return (slp->session);
}
#endif /* NETSNMP_FEATURE_REMOVE_SNMP_OPEN_EX */
static struct session_list *
_sess_copy(netsnmp_session * in_session)
{
struct session_list *slp;
struct snmp_internal_session *isp;
netsnmp_session *session;
struct snmp_secmod_def *sptr;
char *cp;
u_char *ucp;
in_session->s_snmp_errno = 0;
in_session->s_errno = 0;
/*
* Copy session structure and link into list
*/
slp = (struct session_list *) calloc(1, sizeof(struct session_list));
if (slp == NULL) {
in_session->s_snmp_errno = SNMPERR_MALLOC;
return (NULL);
}
slp->transport = NULL;
isp = (struct snmp_internal_session *)calloc(1, sizeof(struct snmp_internal_session));
if (isp == NULL) {
snmp_sess_close(slp);
in_session->s_snmp_errno = SNMPERR_MALLOC;
return (NULL);
}
slp->internal = isp;
slp->session = (netsnmp_session *)malloc(sizeof(netsnmp_session));
if (slp->session == NULL) {
snmp_sess_close(slp);
in_session->s_snmp_errno = SNMPERR_MALLOC;
return (NULL);
}
memmove(slp->session, in_session, sizeof(netsnmp_session));
session = slp->session;
/*
* zero out pointers so if we have to free the session we wont free mem
* owned by in_session
*/
session->localname = NULL;
session->peername = NULL;
session->community = NULL;
session->contextEngineID = NULL;
session->contextName = NULL;
session->securityEngineID = NULL;
session->securityName = NULL;
session->securityAuthProto = NULL;
session->securityPrivProto = NULL;
/*
* session now points to the new structure that still contains pointers to
* data allocated elsewhere. Some of this data is copied to space malloc'd
* here, and the pointer replaced with the new one.
*/
if (in_session->peername != NULL) {
session->peername =
netsnmp_strdup_and_null((u_char*)in_session->peername,
strlen(in_session->peername));
if (session->peername == NULL) {
snmp_sess_close(slp);
in_session->s_snmp_errno = SNMPERR_MALLOC;
return (NULL);
}
}
/*
* Fill in defaults if necessary
*/
#if !defined(NETSNMP_DISABLE_SNMPV1) || !defined(NETSNMP_DISABLE_SNMPV2C)
if (in_session->community_len != SNMP_DEFAULT_COMMUNITY_LEN) {
ucp = (u_char *) malloc(in_session->community_len);
if (ucp != NULL)
memmove(ucp, in_session->community, in_session->community_len);
} else {
if ((cp = netsnmp_ds_get_string(NETSNMP_DS_LIBRARY_ID,
NETSNMP_DS_LIB_COMMUNITY)) != NULL) {
session->community_len = strlen(cp);
ucp = (u_char *) strdup(cp);
} else {
#ifdef NETSNMP_NO_ZEROLENGTH_COMMUNITY
session->community_len = strlen(DEFAULT_COMMUNITY);
ucp = (u_char *) malloc(session->community_len);
if (ucp)
memmove(ucp, DEFAULT_COMMUNITY, session->community_len);
#else
ucp = (u_char *) strdup("");
#endif
}
}
if (ucp == NULL) {
snmp_sess_close(slp);
in_session->s_snmp_errno = SNMPERR_MALLOC;
return (NULL);
}
session->community = ucp; /* replace pointer with pointer to new data */
#endif
if (session->securityLevel <= 0) {
session->securityLevel =
netsnmp_ds_get_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_SECLEVEL);
}
if (in_session->securityEngineIDLen > 0) {
ucp = (u_char *) malloc(in_session->securityEngineIDLen);
if (ucp == NULL) {
snmp_sess_close(slp);
in_session->s_snmp_errno = SNMPERR_MALLOC;
return (NULL);
}
memmove(ucp, in_session->securityEngineID,
in_session->securityEngineIDLen);
session->securityEngineID = ucp;
}
if (in_session->contextEngineIDLen > 0) {
ucp = (u_char *) malloc(in_session->contextEngineIDLen);
if (ucp == NULL) {
snmp_sess_close(slp);
in_session->s_snmp_errno = SNMPERR_MALLOC;
return (NULL);
}
memmove(ucp, in_session->contextEngineID,
in_session->contextEngineIDLen);
session->contextEngineID = ucp;
} else if (in_session->securityEngineIDLen > 0) {
/*
* default contextEngineID to securityEngineIDLen if defined
*/
ucp = (u_char *) malloc(in_session->securityEngineIDLen);
if (ucp == NULL) {
snmp_sess_close(slp);
in_session->s_snmp_errno = SNMPERR_MALLOC;
return (NULL);
}
memmove(ucp, in_session->securityEngineID,
in_session->securityEngineIDLen);
session->contextEngineID = ucp;
session->contextEngineIDLen = in_session->securityEngineIDLen;
}
if (in_session->contextName) {
session->contextName = strdup(in_session->contextName);
if (session->contextName == NULL) {
snmp_sess_close(slp);
return (NULL);
}
session->contextNameLen = in_session->contextNameLen;
} else {
if ((cp = netsnmp_ds_get_string(NETSNMP_DS_LIBRARY_ID,
NETSNMP_DS_LIB_CONTEXT)) != NULL)
cp = strdup(cp);
else
cp = strdup(SNMP_DEFAULT_CONTEXT);
if (cp == NULL) {
snmp_sess_close(slp);
return (NULL);
}
session->contextName = cp;
session->contextNameLen = strlen(cp);
}
if (in_session->securityName) {
session->securityName = strdup(in_session->securityName);
if (session->securityName == NULL) {
snmp_sess_close(slp);
return (NULL);
}
} else if ((cp = netsnmp_ds_get_string(NETSNMP_DS_LIBRARY_ID,
NETSNMP_DS_LIB_SECNAME)) != NULL) {
cp = strdup(cp);
if (cp == NULL) {
snmp_sess_close(slp);
return (NULL);
}
session->securityName = cp;
session->securityNameLen = strlen(cp);
}
if (session->retries == SNMP_DEFAULT_RETRIES) {
int retry = netsnmp_ds_get_int(NETSNMP_DS_LIBRARY_ID,
NETSNMP_DS_LIB_RETRIES);
if (retry < 0)
session->retries = DEFAULT_RETRIES;
else
session->retries = retry;
}
if (session->timeout == SNMP_DEFAULT_TIMEOUT) {
int timeout = netsnmp_ds_get_int(NETSNMP_DS_LIBRARY_ID,
NETSNMP_DS_LIB_TIMEOUT);
if (timeout <= 0)
session->timeout = DEFAULT_TIMEOUT;
else
session->timeout = timeout * ONE_SEC;
}
session->sessid = snmp_get_next_sessid();
snmp_call_callbacks(SNMP_CALLBACK_LIBRARY, SNMP_CALLBACK_SESSION_INIT,
session);
if ((sptr = find_sec_mod(session->securityModel)) != NULL) {
/*
* security module specific copying
*/
if (sptr->session_setup) {
int ret = (*sptr->session_setup) (in_session, session);
if (ret != SNMPERR_SUCCESS) {
snmp_sess_close(slp);
return NULL;
}
}
/*
* security module specific opening
*/
if (sptr->session_open) {
int ret = (*sptr->session_open) (session);
if (ret != SNMPERR_SUCCESS) {
snmp_sess_close(slp);
return NULL;
}
}
}
/* Anything below this point should only be done if the transport
had no say in the matter */
if (session->securityLevel == 0)
session->securityLevel = SNMP_SEC_LEVEL_NOAUTH;
return (slp);
}
static struct session_list *
snmp_sess_copy(netsnmp_session * pss)
{
struct session_list *psl;
psl = _sess_copy(pss);
if (!psl) {
if (!pss->s_snmp_errno) {
pss->s_snmp_errno = SNMPERR_GENERR;
}
SET_SNMP_ERROR(pss->s_snmp_errno);
}
return psl;
}
#ifndef NETSNMP_FEATURE_REMOVE_SNMPV3_PROBE_CONTEXTENGINEID_RFC5343
/**
* probe for engineID using RFC 5343 probing mechanisms
*
* Designed to be a callback for within a security model's probe_engineid hook.
* Since it's likely multiple security models won't have engineIDs to
* probe for then this function is a callback likely to be used by
* multiple future security models. E.G. both SSH and DTLS.
*/
int
snmpv3_probe_contextEngineID_rfc5343(struct session_list *slp,
netsnmp_session *session)
{
netsnmp_pdu *pdu = NULL, *response = NULL;
static oid snmpEngineIDoid[] = { 1,3,6,1,6,3,10,2,1,1,0};
static size_t snmpEngineIDoid_len = 11;
static char probeEngineID[] = { (char)0x80, 0, 0, 0, 6 };
static size_t probeEngineID_len = sizeof(probeEngineID);
int status;
pdu = snmp_pdu_create(SNMP_MSG_GET);
if (!pdu)
return SNMP_ERR_GENERR;
pdu->version = SNMP_VERSION_3;
/* don't require a securityName */
if (session->securityName) {
pdu->securityName = strdup(session->securityName);
pdu->securityNameLen = strlen(pdu->securityName);
}
pdu->securityLevel = SNMP_SEC_LEVEL_NOAUTH;
pdu->securityModel = session->securityModel;
pdu->contextEngineID = netsnmp_memdup(probeEngineID, probeEngineID_len);
if (!pdu->contextEngineID) {
snmp_log(LOG_ERR, "failed to clone memory for rfc5343 probe\n");
snmp_free_pdu(pdu);
return SNMP_ERR_GENERR;
}
pdu->contextEngineIDLen = probeEngineID_len;
snmp_add_null_var(pdu, snmpEngineIDoid, snmpEngineIDoid_len);
DEBUGMSGTL(("snmp_api", "probing for engineID using rfc5343 methods...\n"));
session->flags |= SNMP_FLAGS_DONT_PROBE; /* prevent recursion */
status = snmp_sess_synch_response(slp, pdu, &response);
if ((response == NULL) || (status != STAT_SUCCESS)) {
snmp_log(LOG_ERR, "failed rfc5343 contextEngineID probing\n");
return SNMP_ERR_GENERR;
}
/* check that the response makes sense */
if (NULL != response->variables &&
NULL != response->variables->name &&
snmp_oid_compare(response->variables->name,
response->variables->name_length,
snmpEngineIDoid, snmpEngineIDoid_len) == 0 &&
ASN_OCTET_STR == response->variables->type &&
NULL != response->variables->val.string &&
response->variables->val_len > 0) {
session->contextEngineID =
netsnmp_memdup(response->variables->val.string,
response->variables->val_len);
if (!session->contextEngineID) {
snmp_log(LOG_ERR, "failed rfc5343 contextEngineID probing: memory allocation failed\n");
return SNMP_ERR_GENERR;
}
/* technically there likely isn't a securityEngineID but just
in case anyone goes looking we might as well have one */
session->securityEngineID =
netsnmp_memdup(response->variables->val.string,
response->variables->val_len);
if (!session->securityEngineID) {
snmp_log(LOG_ERR, "failed rfc5343 securityEngineID probing: memory allocation failed\n");
return SNMP_ERR_GENERR;
}
session->securityEngineIDLen = session->contextEngineIDLen =
response->variables->val_len;
if (snmp_get_do_debugging()) {
size_t i;
DEBUGMSGTL(("snmp_sess_open",
" probe found engineID: "));
for (i = 0; i < session->securityEngineIDLen; i++)
DEBUGMSG(("snmp_sess_open", "%02x",
session->securityEngineID[i]));
DEBUGMSG(("snmp_sess_open", "\n"));
}
}
return SNMPERR_SUCCESS;
}
#endif /* NETSNMP_FEATURE_REMOVE_SNMPV3_PROBE_CONTEXTENGINEID_RFC5343 */
/**
* probe for peer engineID
*
* @param slp session list pointer.
* @param in_session session for errors
*
* @note
* - called by _sess_open(), snmp_sess_add_ex()
* - in_session is the user supplied session provided to those functions.
* - the first session in slp should the internal allocated copy of in_session
*
* @return 0 : error
* @return 1 : ok
*
*/
int
snmpv3_engineID_probe(struct session_list *slp,
netsnmp_session * in_session)
{
netsnmp_session *session;
int status;
struct snmp_secmod_def *sptr = NULL;
if (slp == NULL || slp->session == NULL) {
return 0;
}
session = slp->session;
netsnmp_assert_or_return(session != NULL, 0);
sptr = find_sec_mod(session->securityModel);
/*
* If we are opening a V3 session and we don't know engineID we must probe
* it -- this must be done after the session is created and inserted in the
* list so that the response can handled correctly.
*/
if (session->version == SNMP_VERSION_3 &&
(0 == (session->flags & SNMP_FLAGS_DONT_PROBE))) {
if (NULL != sptr && NULL != sptr->probe_engineid) {
DEBUGMSGTL(("snmp_api", "probing for engineID using security model callback...\n"));
/* security model specific mechanism of determining engineID */
status = (*sptr->probe_engineid) (slp, in_session);
if (status != SNMPERR_SUCCESS)
return 0;
} else {
/* XXX: default to the default RFC5343 contextEngineID Probe? */
return 0;
}
}
/*
* see if there is a hook to call now that we're done probing for an
* engineID
*/
if (sptr && sptr->post_probe_engineid) {
status = (*sptr->post_probe_engineid)(slp, in_session);
if (status != SNMPERR_SUCCESS)
return 0;
}
return 1;
}
/*******************************************************************-o-******
* netsnmp_sess_config_transport
*
* Parameters:
* *in_session
* *in_transport
*
* Returns:
* SNMPERR_SUCCESS - Yay
* SNMPERR_GENERR - Generic Error
* SNMPERR_TRANSPORT_CONFIG_ERROR - Transport rejected config
* SNMPERR_TRANSPORT_NO_CONFIG - Transport can't config
*/
int
netsnmp_sess_config_transport(netsnmp_container *transport_configuration,
netsnmp_transport *transport)
{
/* Optional supplimental transport configuration information and
final call to actually open the transport */
if (transport_configuration) {
DEBUGMSGTL(("snmp_sess", "configuring transport\n"));
if (transport->f_config) {
netsnmp_iterator *iter;
netsnmp_transport_config *config_data;
int ret = 0;
iter = CONTAINER_ITERATOR(transport_configuration);
if (NULL == iter) {
return SNMPERR_GENERR;
}
for(config_data = (netsnmp_transport_config*)ITERATOR_FIRST(iter); config_data;
config_data = (netsnmp_transport_config*)ITERATOR_NEXT(iter)) {
ret = transport->f_config(transport, config_data->key,
config_data->value);
if (ret)
break;
}
ITERATOR_RELEASE(iter);
if (ret)
return SNMPERR_TRANSPORT_CONFIG_ERROR;
} else {
return SNMPERR_TRANSPORT_NO_CONFIG;
}
}
return SNMPERR_SUCCESS;
}
/**
* Copies configuration from the session and calls f_open
* This function copies any configuration stored in the session
* pointer to the transport if it has a f_config pointer and then
* calls the transport's f_open function to actually open the
* connection.
*
* @param in_session A pointer to the session that config information is in.
* @param transport A pointer to the transport to config/open.
*
* @return SNMPERR_SUCCESS : on success
*/
/*******************************************************************-o-******
* netsnmp_sess_config_transport
*
* Parameters:
* *in_session
* *in_transport
*
* Returns:
* SNMPERR_SUCCESS - Yay
* SNMPERR_GENERR - Generic Error
* SNMPERR_TRANSPORT_CONFIG_ERROR - Transport rejected config
* SNMPERR_TRANSPORT_NO_CONFIG - Transport can't config
*/
int
netsnmp_sess_config_and_open_transport(netsnmp_session *in_session,
netsnmp_transport *transport)
{
int rc;
DEBUGMSGTL(("snmp_sess", "opening transport: %x\n", transport->flags & NETSNMP_TRANSPORT_FLAG_OPENED));
/* don't double open */
if (transport->flags & NETSNMP_TRANSPORT_FLAG_OPENED)
return SNMPERR_SUCCESS;
if ((rc = netsnmp_sess_config_transport(in_session->transport_configuration,
transport)) != SNMPERR_SUCCESS) {
in_session->s_snmp_errno = rc;
in_session->s_errno = 0;
return rc;
}
if (transport->f_open)
transport = transport->f_open(transport);
if (transport == NULL) {
DEBUGMSGTL(("snmp_sess", "couldn't interpret peername\n"));
in_session->s_snmp_errno = SNMPERR_BAD_ADDRESS;
in_session->s_errno = errno;
snmp_set_detail(in_session->peername);
return SNMPERR_BAD_ADDRESS;
}
/** if transport has a max size, make sure session is the same (or less) */
if (in_session->rcvMsgMaxSize > transport->msgMaxSize) {
DEBUGMSGTL(("snmp_sess",
"limiting session rcv size (%" NETSNMP_PRIz "d) to transport max (%" NETSNMP_PRIz "d)\n",
in_session->rcvMsgMaxSize, transport->msgMaxSize));
in_session->rcvMsgMaxSize = transport->msgMaxSize;
}
if (in_session->sndMsgMaxSize > transport->msgMaxSize) {
DEBUGMSGTL(("snmp_sess",
"limiting session snd size (%" NETSNMP_PRIz "d) to transport max (%" NETSNMP_PRIz "d)\n",
in_session->sndMsgMaxSize, transport->msgMaxSize));
in_session->sndMsgMaxSize = transport->msgMaxSize;
}
transport->flags |= NETSNMP_TRANSPORT_FLAG_OPENED;
DEBUGMSGTL(("snmp_sess", "done opening transport: %x\n", transport->flags & NETSNMP_TRANSPORT_FLAG_OPENED));
return SNMPERR_SUCCESS;
}
/*******************************************************************-o-******
* snmp_sess_open
*
* Parameters:
* *in_session
*
* Returns:
* Pointer to a session in the session list -OR- FIX -- right?
* NULL on failure.
*
* The "spin-free" version of snmp_open.
*/
static void *
_sess_open(netsnmp_session * in_session)
{
netsnmp_transport *transport = NULL;
int rc;
in_session->s_snmp_errno = 0;
in_session->s_errno = 0;
_init_snmp();
{
char *clientaddr_save = NULL;
if (NULL != in_session->localname) {
clientaddr_save =
netsnmp_ds_get_string(NETSNMP_DS_LIBRARY_ID,
NETSNMP_DS_LIB_CLIENT_ADDR);
if (clientaddr_save)
clientaddr_save = strdup(clientaddr_save);
netsnmp_ds_set_string(NETSNMP_DS_LIBRARY_ID,
NETSNMP_DS_LIB_CLIENT_ADDR,
in_session->localname);
}
if (in_session->flags & SNMP_FLAGS_STREAM_SOCKET) {
transport =
netsnmp_tdomain_transport_full("snmp", in_session->peername,
in_session->local_port, "tcp,tcp6",
NULL);
} else {
transport =
netsnmp_tdomain_transport_full("snmp", in_session->peername,
in_session->local_port, "udp,udp6",
NULL);
}
if (NULL != in_session->localname)
netsnmp_ds_set_string(NETSNMP_DS_LIBRARY_ID,
NETSNMP_DS_LIB_CLIENT_ADDR, clientaddr_save);
free(clientaddr_save);
}
if (transport == NULL) {
DEBUGMSGTL(("_sess_open", "couldn't interpret peername\n"));
in_session->s_snmp_errno = SNMPERR_BAD_ADDRESS;
in_session->s_errno = errno;
snmp_set_detail(in_session->peername);
return NULL;
}
/* Optional supplimental transport configuration information and
final call to actually open the transport */
if ((rc = netsnmp_sess_config_and_open_transport(in_session, transport))
!= SNMPERR_SUCCESS) {
transport = NULL;
return NULL;
}
#if defined(SO_BROADCAST) && defined(SOL_SOCKET)
if ( in_session->flags & SNMP_FLAGS_UDP_BROADCAST) {
int b = 1;
int rc;
rc = setsockopt(transport->sock, SOL_SOCKET, SO_BROADCAST,
(char *)&b, sizeof(b));
if ( rc != 0 ) {
in_session->s_snmp_errno = SNMPERR_BAD_ADDRESS; /* good as any? */
in_session->s_errno = errno;
DEBUGMSGTL(("_sess_open", "couldn't enable UDP_BROADCAST\n"));
return NULL;
}
}
#endif
return snmp_sess_add(in_session, transport, NULL, NULL);
}
/*
* EXTENDED SESSION API ------------------------------------------
*
* snmp_sess_add_ex, snmp_sess_add, snmp_add
*
* Analogous to snmp_open family of functions, but taking a netsnmp_transport
* pointer as an extra argument. Unlike snmp_open et al. it doesn't attempt
* to interpret the in_session->peername as a transport endpoint specifier,
* but instead uses the supplied transport. JBPN
*
*/
netsnmp_session *
snmp_add(netsnmp_session * in_session,
netsnmp_transport *transport,
int (*fpre_parse) (netsnmp_session *, netsnmp_transport *, void *,
int), int (*fpost_parse) (netsnmp_session *,
netsnmp_pdu *, int))
{
struct session_list *slp;
slp = (struct session_list *) snmp_sess_add_ex(in_session, transport,
fpre_parse, NULL,
fpost_parse, NULL, NULL,
NULL, NULL);
if (slp == NULL) {
return NULL;
}
snmp_session_insert(slp);
return (slp->session);
}
netsnmp_session *
snmp_add_full(netsnmp_session * in_session,
netsnmp_transport *transport,
int (*fpre_parse) (netsnmp_session *, netsnmp_transport *,
void *, int),
int (*fparse) (netsnmp_session *, netsnmp_pdu *, u_char *,
size_t),
int (*fpost_parse) (netsnmp_session *, netsnmp_pdu *, int),
int (*fbuild) (netsnmp_session *, netsnmp_pdu *, u_char *,
size_t *), int (*frbuild) (netsnmp_session *,
netsnmp_pdu *,
u_char **,
size_t *,
size_t *),
int (*fcheck) (u_char *, size_t),
netsnmp_pdu *(*fcreate_pdu) (netsnmp_transport *, void *,
size_t))
{
struct session_list *slp;
slp = (struct session_list *) snmp_sess_add_ex(in_session, transport,
fpre_parse, fparse,
fpost_parse, fbuild,
frbuild, fcheck,
fcreate_pdu);
if (slp == NULL) {
return NULL;
}
snmp_session_insert(slp);
return (slp->session);
}
void *
snmp_sess_add_ex(netsnmp_session * in_session,
netsnmp_transport *transport,
int (*fpre_parse) (netsnmp_session *, netsnmp_transport *,
void *, int),
int (*fparse) (netsnmp_session *, netsnmp_pdu *, u_char *,
size_t),
int (*fpost_parse) (netsnmp_session *, netsnmp_pdu *,
int),
int (*fbuild) (netsnmp_session *, netsnmp_pdu *, u_char *,
size_t *),
int (*frbuild) (netsnmp_session *, netsnmp_pdu *,
u_char **, size_t *, size_t *),
int (*fcheck) (u_char *, size_t),
netsnmp_pdu *(*fcreate_pdu) (netsnmp_transport *, void *,
size_t))
{
struct session_list *slp;
int rc;
_init_snmp();
if (transport == NULL)
return NULL;
if (NULL != in_session && (in_session->rcvMsgMaxSize < SNMP_MIN_MAX_LEN ||
in_session->sndMsgMaxSize < SNMP_MIN_MAX_LEN)) {
DEBUGMSGTL(("snmp_sess_add",
"invalid session (msg sizes). need snmp_sess_init"));
in_session = NULL; /* force transport cleanup below */
}
if (in_session == NULL) {
transport->f_close(transport);
netsnmp_transport_free(transport);
return NULL;
}
/* if the transport hasn't been fully opened yet, open it now */
if ((rc = netsnmp_sess_config_and_open_transport(in_session, transport))
!= SNMPERR_SUCCESS) {
return NULL;
}
if (transport->f_setup_session) {
if (SNMPERR_SUCCESS !=
transport->f_setup_session(transport, in_session)) {
netsnmp_transport_free(transport);
return NULL;
}
}
DEBUGMSGTL(("snmp_sess_add", "fd %d\n", transport->sock));
if ((slp = snmp_sess_copy(in_session)) == NULL) {
transport->f_close(transport);
netsnmp_transport_free(transport);
return (NULL);
}
slp->transport = transport;
slp->internal->hook_pre = fpre_parse;
slp->internal->hook_parse = fparse;
slp->internal->hook_post = fpost_parse;
slp->internal->hook_build = fbuild;
slp->internal->hook_realloc_build = frbuild;
slp->internal->check_packet = fcheck;
slp->internal->hook_create_pdu = fcreate_pdu;
/** don't let session max exceed transport max */
if (slp->session->rcvMsgMaxSize > transport->msgMaxSize) {
DEBUGMSGTL(("snmp_sess_add",
"limiting session rcv size (%" NETSNMP_PRIz "d) to transport max (%" NETSNMP_PRIz "d)\n",
slp->session->rcvMsgMaxSize, transport->msgMaxSize));
slp->session->rcvMsgMaxSize = transport->msgMaxSize;
}
if (slp->session->sndMsgMaxSize > transport->msgMaxSize) {
DEBUGMSGTL(("snmp_sess_add",
"limiting session snd size (%" NETSNMP_PRIz "d) to transport max (%" NETSNMP_PRIz "d)\n",
slp->session->sndMsgMaxSize, transport->msgMaxSize));
slp->session->sndMsgMaxSize = transport->msgMaxSize;
}
if (slp->session->version == SNMP_VERSION_3) {
DEBUGMSGTL(("snmp_sess_add",
"adding v3 session -- maybe engineID probe now\n"));
if (!snmpv3_engineID_probe(slp, slp->session)) {
DEBUGMSGTL(("snmp_sess_add", "engine ID probe failed\n"));
snmp_sess_close(slp);
return NULL;
}
}
slp->session->flags &= ~SNMP_FLAGS_DONT_PROBE;
return (void *) slp;
} /* end snmp_sess_add_ex() */
void *
snmp_sess_add(netsnmp_session * in_session,
netsnmp_transport *transport,
int (*fpre_parse) (netsnmp_session *, netsnmp_transport *,
void *, int),
int (*fpost_parse) (netsnmp_session *, netsnmp_pdu *, int))
{
return snmp_sess_add_ex(in_session, transport, fpre_parse, NULL,
fpost_parse, NULL, NULL, NULL, NULL);
}
void *
snmp_sess_open(netsnmp_session * pss)
{
void *pvoid;
pvoid = _sess_open(pss);
if (!pvoid) {
SET_SNMP_ERROR(pss->s_snmp_errno);
}
return pvoid;
}
int
create_user_from_session(netsnmp_session * session) {
#ifdef NETSNMP_SECMOD_USM
return usm_create_user_from_session(session);
#else
snmp_log(LOG_ERR, "create_user_from_session called when USM wasn't compiled in");
netsnmp_assert(0 == 1);
return SNMP_ERR_GENERR;
#endif
}
/*
* Do a "deep free()" of a netsnmp_session.
*
* CAUTION: SHOULD ONLY BE USED FROM snmp_sess_close() OR SIMILAR.
* (hence it is static)
*/
static void
snmp_free_session(netsnmp_session * s)
{
if (s) {
SNMP_FREE(s->localname);
SNMP_FREE(s->peername);
SNMP_FREE(s->community);
SNMP_FREE(s->contextEngineID);
SNMP_FREE(s->contextName);
SNMP_FREE(s->securityEngineID);
SNMP_FREE(s->securityName);
SNMP_FREE(s->securityAuthProto);
SNMP_FREE(s->securityPrivProto);
SNMP_FREE(s->paramName);
#ifndef NETSNMP_NO_TRAP_STATS
SNMP_FREE(s->trap_stats);
#endif /* NETSNMP_NO_TRAP_STATS */
/*
* clear session from any callbacks
*/
netsnmp_callback_clear_client_arg(s, 0, 0);
free((char *) s);
}
}
/*
* Close the input session. Frees all data allocated for the session,
* dequeues any pending requests, and closes any sockets allocated for
* the session. Returns 0 on error, 1 otherwise.
*/
int
snmp_sess_close(void *sessp)
{
struct session_list *slp = (struct session_list *) sessp;
netsnmp_transport *transport;
struct snmp_internal_session *isp;
netsnmp_session *sesp = NULL;
struct snmp_secmod_def *sptr;
if (slp == NULL) {
return 0;
}
if (slp->session != NULL &&
(sptr = find_sec_mod(slp->session->securityModel)) != NULL &&
sptr->session_close != NULL) {
(*sptr->session_close) (slp->session);
}
isp = slp->internal;
slp->internal = NULL;
if (isp) {
netsnmp_request_list *rp, *orp;
SNMP_FREE(isp->packet);
/*
* Free each element in the input request list.
*/
rp = isp->requests;
while (rp) {
orp = rp;
rp = rp->next_request;
if (orp->callback) {
orp->callback(NETSNMP_CALLBACK_OP_TIMED_OUT,
slp->session, orp->pdu->reqid,
orp->pdu, orp->cb_data);
}
snmp_free_pdu(orp->pdu);
free((char *) orp);
}
free((char *) isp);
}
transport = slp->transport;
slp->transport = NULL;
if (transport) {
transport->f_close(transport);
netsnmp_transport_free(transport);
}
sesp = slp->session;
slp->session = NULL;
/*
* The following is necessary to avoid memory leakage when closing AgentX
* sessions that may have multiple subsessions. These hang off the main
* session at ->subsession, and chain through ->next.
*/
if (sesp != NULL && sesp->subsession != NULL) {
netsnmp_session *subsession = sesp->subsession, *tmpsub;
while (subsession != NULL) {
DEBUGMSGTL(("snmp_sess_close",
"closing session %p, subsession %p\n", sesp,
subsession));
tmpsub = subsession->next;
snmp_free_session(subsession);
subsession = tmpsub;
}
}
snmp_free_session(sesp);
free((char *) slp);
return 1;
}
int
snmp_close(netsnmp_session * session)
{
struct session_list *slp = NULL, *oslp = NULL;
{ /*MTCRITICAL_RESOURCE */
snmp_res_lock(MT_LIBRARY_ID, MT_LIB_SESSION);
if (Sessions && Sessions->session == session) { /* If first entry */
slp = Sessions;
Sessions = slp->next;
} else {
for (slp = Sessions; slp; slp = slp->next) {
if (slp->session == session) {
if (oslp) /* if we found entry that points here */
oslp->next = slp->next; /* link around this entry */
break;
}
oslp = slp;
}
}
snmp_res_unlock(MT_LIBRARY_ID, MT_LIB_SESSION);
} /*END MTCRITICAL_RESOURCE */
if (slp == NULL) {
return 0;
}
return snmp_sess_close((void *) slp);
}
int
snmp_close_sessions(void)
{
struct session_list *slp;
snmp_res_lock(MT_LIBRARY_ID, MT_LIB_SESSION);
while (Sessions) {
slp = Sessions;
Sessions = Sessions->next;
snmp_sess_close((void *) slp);
}
snmp_res_unlock(MT_LIBRARY_ID, MT_LIB_SESSION);
return 1;
}
static void
snmpv3_calc_msg_flags(int sec_level, int msg_command, u_char * flags)
{
*flags = 0;
if (sec_level == SNMP_SEC_LEVEL_AUTHNOPRIV)
*flags = SNMP_MSG_FLAG_AUTH_BIT;
else if (sec_level == SNMP_SEC_LEVEL_AUTHPRIV)
*flags = SNMP_MSG_FLAG_AUTH_BIT | SNMP_MSG_FLAG_PRIV_BIT;
if (SNMP_CMD_CONFIRMED(msg_command))
*flags |= SNMP_MSG_FLAG_RPRT_BIT;
return;
}
static int
snmpv3_verify_msg(netsnmp_request_list *rp, netsnmp_pdu *pdu)
{
netsnmp_pdu *rpdu;
if (!rp || !rp->pdu || !pdu)
return 0;
/*
* Reports don't have to match anything according to the spec
*/
if (pdu->command == SNMP_MSG_REPORT)
return 1;
rpdu = rp->pdu;
if (rp->request_id != pdu->reqid || rpdu->reqid != pdu->reqid)
return 0;
if (rpdu->version != pdu->version)
return 0;
if (rpdu->securityModel != pdu->securityModel)
return 0;
if (rpdu->securityLevel != pdu->securityLevel)
return 0;
if (rpdu->contextEngineIDLen != pdu->contextEngineIDLen ||
memcmp(rpdu->contextEngineID, pdu->contextEngineID,
pdu->contextEngineIDLen))
return 0;
if (rpdu->contextNameLen != pdu->contextNameLen ||
memcmp(rpdu->contextName, pdu->contextName, pdu->contextNameLen))
return 0;
/* tunneled transports don't have a securityEngineID... that's
USM specific (and maybe other future ones) */
if (pdu->securityModel == SNMP_SEC_MODEL_USM &&
(rpdu->securityEngineIDLen != pdu->securityEngineIDLen ||
memcmp(rpdu->securityEngineID, pdu->securityEngineID,
pdu->securityEngineIDLen)))
return 0;
/* the securityName must match though regardless of secmodel */
if (rpdu->securityNameLen != pdu->securityNameLen ||
memcmp(rpdu->securityName, pdu->securityName,
pdu->securityNameLen))
return 0;
return 1;
}
/*
* SNMPv3
* * Takes a session and a pdu and serializes the ASN PDU into the area
* * pointed to by packet. out_length is the size of the data area available.
* * Returns the length of the completed packet in out_length. If any errors
* * occur, -1 is returned. If all goes well, 0 is returned.
*/
static int
snmpv3_build(u_char ** pkt, size_t * pkt_len, size_t * offset,
netsnmp_session * session, netsnmp_pdu *pdu)
{
int ret;
session->s_snmp_errno = 0;
session->s_errno = 0;
/*
* do validation for PDU types
*/
switch (pdu->command) {
case SNMP_MSG_RESPONSE:
case SNMP_MSG_TRAP2:
case SNMP_MSG_REPORT:
netsnmp_assert(0 == (pdu->flags & UCD_MSG_FLAG_EXPECT_RESPONSE));
/* FALL THROUGH */
case SNMP_MSG_INFORM:
#ifndef NETSNMP_NOTIFY_ONLY
case SNMP_MSG_GET:
case SNMP_MSG_GETNEXT:
#endif /* ! NETSNMP_NOTIFY_ONLY */
#ifndef NETSNMP_NO_WRITE_SUPPORT
case SNMP_MSG_SET:
#endif /* !NETSNMP_NO_WRITE_SUPPORT */
if (pdu->errstat == SNMP_DEFAULT_ERRSTAT)
pdu->errstat = 0;
if (pdu->errindex == SNMP_DEFAULT_ERRINDEX)
pdu->errindex = 0;
break;
#ifndef NETSNMP_NOTIFY_ONLY
case SNMP_MSG_GETBULK:
if (pdu->max_repetitions < 0) {
session->s_snmp_errno = SNMPERR_BAD_REPETITIONS;
return -1;
}
if (pdu->non_repeaters < 0) {
session->s_snmp_errno = SNMPERR_BAD_REPEATERS;
return -1;
}
break;
#endif /* ! NETSNMP_NOTIFY_ONLY */
case SNMP_MSG_TRAP:
session->s_snmp_errno = SNMPERR_V1_IN_V2;
return -1;
default:
session->s_snmp_errno = SNMPERR_UNKNOWN_PDU;
return -1;
}
/* Do we need to set the session security engineid? */
if (pdu->securityEngineIDLen == 0) {
if (session->securityEngineIDLen) {
snmpv3_clone_engineID(&pdu->securityEngineID,
&pdu->securityEngineIDLen,
session->securityEngineID,
session->securityEngineIDLen);
}
}
/* Do we need to set the session context engineid? */
if (pdu->contextEngineIDLen == 0) {
if (session->contextEngineIDLen) {
snmpv3_clone_engineID(&pdu->contextEngineID,
&pdu->contextEngineIDLen,
session->contextEngineID,
session->contextEngineIDLen);
} else if (pdu->securityEngineIDLen) {
snmpv3_clone_engineID(&pdu->contextEngineID,
&pdu->contextEngineIDLen,
pdu->securityEngineID,
pdu->securityEngineIDLen);
}
}
if (pdu->contextName == NULL) {
if (!session->contextName) {
session->s_snmp_errno = SNMPERR_BAD_CONTEXT;
return -1;
}
pdu->contextName = strdup(session->contextName);
if (pdu->contextName == NULL) {
session->s_snmp_errno = SNMPERR_GENERR;
return -1;
}
pdu->contextNameLen = session->contextNameLen;
}
if (pdu->securityModel == SNMP_DEFAULT_SECMODEL) {
pdu->securityModel = session->securityModel;
if (pdu->securityModel == SNMP_DEFAULT_SECMODEL) {
pdu->securityModel = se_find_value_in_slist("snmp_secmods", netsnmp_ds_get_string(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_SECMODEL));
if (pdu->securityModel <= 0) {
pdu->securityModel = SNMP_SEC_MODEL_USM;
}
}
}
if (pdu->securityNameLen == 0 && pdu->securityName == NULL) {
if (session->securityModel != SNMP_SEC_MODEL_TSM &&
session->securityNameLen == 0) {
session->s_snmp_errno = SNMPERR_BAD_SEC_NAME;
return -1;
}
if (session->securityName) {
pdu->securityName = strdup(session->securityName);
if (pdu->securityName == NULL) {
session->s_snmp_errno = SNMPERR_GENERR;
return -1;
}
pdu->securityNameLen = session->securityNameLen;
} else {
pdu->securityName = strdup("");
session->securityName = strdup("");
}
}
if (pdu->securityLevel == 0) {
if (session->securityLevel == 0) {
session->s_snmp_errno = SNMPERR_BAD_SEC_LEVEL;
return -1;
}
pdu->securityLevel = session->securityLevel;
}
DEBUGMSGTL(("snmp_build",
"Building SNMPv3 message (secName:\"%s\", secLevel:%s)...\n",
((session->securityName) ? (char *) session->securityName :
((pdu->securityName) ? (char *) pdu->securityName :
"ERROR: undefined")), secLevelName[pdu->securityLevel]));
DEBUGDUMPSECTION("send", "SNMPv3 Message");
#ifdef NETSNMP_USE_REVERSE_ASNENCODING
if (!(pdu->flags & UCD_MSG_FLAG_FORWARD_ENCODE)) {
ret = snmpv3_packet_realloc_rbuild(pkt, pkt_len, offset,
session, pdu, NULL, 0);
} else {
#endif
ret = snmpv3_packet_build(session, pdu, *pkt, pkt_len, NULL, 0);
#ifdef NETSNMP_USE_REVERSE_ASNENCODING
}
#endif
DEBUGINDENTLESS();
if (-1 != ret) {
session->s_snmp_errno = ret;
}
return ret;
} /* end snmpv3_build() */
static u_char *
snmpv3_header_build(netsnmp_session * session, netsnmp_pdu *pdu,
u_char * packet, size_t * out_length,
size_t length, u_char ** msg_hdr_e)
{
u_char *global_hdr, *global_hdr_e;
u_char *cp;
u_char msg_flags;
long max_size;
long sec_model;
u_char *pb, *pb0e;
/*
* Save current location and build SEQUENCE tag and length placeholder
* * for SNMP message sequence (actual length inserted later)
*/
cp = asn_build_sequence(packet, out_length,
(u_char) (ASN_SEQUENCE | ASN_CONSTRUCTOR),
length);
if (cp == NULL)
return NULL;
if (msg_hdr_e != NULL)
*msg_hdr_e = cp;
pb0e = cp;
/*
* store the version field - msgVersion
*/
DEBUGDUMPHEADER("send", "SNMP Version Number");
cp = asn_build_int(cp, out_length,
(u_char) (ASN_UNIVERSAL | ASN_PRIMITIVE |
ASN_INTEGER), (long *) &pdu->version,
sizeof(pdu->version));
DEBUGINDENTLESS();
if (cp == NULL)
return NULL;
global_hdr = cp;
/*
* msgGlobalData HeaderData
*/
DEBUGDUMPSECTION("send", "msgGlobalData");
cp = asn_build_sequence(cp, out_length,
(u_char) (ASN_SEQUENCE | ASN_CONSTRUCTOR), 0);
if (cp == NULL)
return NULL;
global_hdr_e = cp;
/*
* msgID
*/
DEBUGDUMPHEADER("send", "msgID");
cp = asn_build_int(cp, out_length,
(u_char) (ASN_UNIVERSAL | ASN_PRIMITIVE |
ASN_INTEGER), &pdu->msgid,
sizeof(pdu->msgid));
DEBUGINDENTLESS();
if (cp == NULL)
return NULL;
/*
* msgMaxSize
*/
max_size = netsnmp_max_send_msg_size();
if (session->rcvMsgMaxSize < max_size)
max_size = session->rcvMsgMaxSize;
DEBUGDUMPHEADER("send:msgMaxSize1", "msgMaxSize");
cp = asn_build_int(cp, out_length,
(u_char) (ASN_UNIVERSAL | ASN_PRIMITIVE |
ASN_INTEGER), &max_size,
sizeof(max_size));
DEBUGINDENTLESS();
if (cp == NULL)
return NULL;
/*
* msgFlags
*/
snmpv3_calc_msg_flags(pdu->securityLevel, pdu->command, &msg_flags);
DEBUGDUMPHEADER("send", "msgFlags");
cp = asn_build_string(cp, out_length,
(u_char) (ASN_UNIVERSAL | ASN_PRIMITIVE |
ASN_OCTET_STR), &msg_flags,
sizeof(msg_flags));
DEBUGINDENTLESS();
if (cp == NULL)
return NULL;
/*
* msgSecurityModel
*/
sec_model = pdu->securityModel;
DEBUGDUMPHEADER("send", "msgSecurityModel");
cp = asn_build_int(cp, out_length,
(u_char) (ASN_UNIVERSAL | ASN_PRIMITIVE |
ASN_INTEGER), &sec_model,
sizeof(sec_model));
DEBUGINDENTADD(-4); /* return from global data indent */
if (cp == NULL)
return NULL;
/*
* insert actual length of globalData
*/
pb = asn_build_sequence(global_hdr, out_length,
(u_char) (ASN_SEQUENCE | ASN_CONSTRUCTOR),
cp - global_hdr_e);
if (pb == NULL)
return NULL;
/*
* insert the actual length of the entire packet
*/
pb = asn_build_sequence(packet, out_length,
(u_char) (ASN_SEQUENCE | ASN_CONSTRUCTOR),
length + (cp - pb0e));
if (pb == NULL)
return NULL;
return cp;
} /* end snmpv3_header_build() */
#ifdef NETSNMP_USE_REVERSE_ASNENCODING
int
snmpv3_header_realloc_rbuild(u_char ** pkt, size_t * pkt_len,
size_t * offset, netsnmp_session * session,
netsnmp_pdu *pdu)
{
size_t start_offset = *offset;
u_char msg_flags;
long max_size, sec_model;
int rc = 0;
/*
* msgSecurityModel.
*/
sec_model = pdu->securityModel;
DEBUGDUMPHEADER("send", "msgSecurityModel");
rc = asn_realloc_rbuild_int(pkt, pkt_len, offset, 1,
(u_char) (ASN_UNIVERSAL | ASN_PRIMITIVE |
ASN_INTEGER), &sec_model,
sizeof(sec_model));
DEBUGINDENTLESS();
if (rc == 0) {
return 0;
}
/*
* msgFlags.
*/
snmpv3_calc_msg_flags(pdu->securityLevel, pdu->command, &msg_flags);
DEBUGDUMPHEADER("send", "msgFlags");
rc = asn_realloc_rbuild_string(pkt, pkt_len, offset, 1,
(u_char) (ASN_UNIVERSAL | ASN_PRIMITIVE
| ASN_OCTET_STR), &msg_flags,
sizeof(msg_flags));
DEBUGINDENTLESS();
if (rc == 0) {
return 0;
}
/*
* msgMaxSize.
*/
max_size = netsnmp_max_send_msg_size();
if (session->rcvMsgMaxSize < max_size)
max_size = session->rcvMsgMaxSize;
DEBUGDUMPHEADER("send:msgMaxSize2", "msgMaxSize");
rc = asn_realloc_rbuild_int(pkt, pkt_len, offset, 1,
(u_char) (ASN_UNIVERSAL | ASN_PRIMITIVE |
ASN_INTEGER), &max_size,
sizeof(max_size));
DEBUGINDENTLESS();
if (rc == 0) {
return 0;
}
/*
* msgID.
*/
DEBUGDUMPHEADER("send", "msgID");
rc = asn_realloc_rbuild_int(pkt, pkt_len, offset, 1,
(u_char) (ASN_UNIVERSAL | ASN_PRIMITIVE |
ASN_INTEGER), &pdu->msgid,
sizeof(pdu->msgid));
DEBUGINDENTLESS();
if (rc == 0) {
return 0;
}
/*
* Global data sequence.
*/
rc = asn_realloc_rbuild_sequence(pkt, pkt_len, offset, 1,
(u_char) (ASN_SEQUENCE |
ASN_CONSTRUCTOR),
*offset - start_offset);
if (rc == 0) {
return 0;
}
/*
* Store the version field - msgVersion.
*/
DEBUGDUMPHEADER("send", "SNMP Version Number");
rc = asn_realloc_rbuild_int(pkt, pkt_len, offset, 1,
(u_char) (ASN_UNIVERSAL | ASN_PRIMITIVE |
ASN_INTEGER),
(long *) &pdu->version,
sizeof(pdu->version));
DEBUGINDENTLESS();
return rc;
} /* end snmpv3_header_realloc_rbuild() */
#endif /* NETSNMP_USE_REVERSE_ASNENCODING */
static u_char *
snmpv3_scopedPDU_header_build(netsnmp_pdu *pdu,
u_char * packet, size_t * out_length,
u_char ** spdu_e)
{
u_char *scopedPdu, *pb;
pb = scopedPdu = packet;
pb = asn_build_sequence(pb, out_length,
(u_char) (ASN_SEQUENCE | ASN_CONSTRUCTOR), 0);
if (pb == NULL)
return NULL;
if (spdu_e)
*spdu_e = pb;
DEBUGDUMPHEADER("send", "contextEngineID");
pb = asn_build_string(pb, out_length,
(ASN_UNIVERSAL | ASN_PRIMITIVE | ASN_OCTET_STR),
pdu->contextEngineID, pdu->contextEngineIDLen);
DEBUGINDENTLESS();
if (pb == NULL)
return NULL;
DEBUGDUMPHEADER("send", "contextName");
pb = asn_build_string(pb, out_length,
(ASN_UNIVERSAL | ASN_PRIMITIVE | ASN_OCTET_STR),
(u_char *) pdu->contextName,
pdu->contextNameLen);
DEBUGINDENTLESS();
if (pb == NULL)
return NULL;
return pb;
} /* end snmpv3_scopedPDU_header_build() */
#ifdef NETSNMP_USE_REVERSE_ASNENCODING
int
snmpv3_scopedPDU_header_realloc_rbuild(u_char ** pkt, size_t * pkt_len,
size_t * offset, netsnmp_pdu *pdu,
size_t body_len)
{
size_t start_offset = *offset;
int rc = 0;
/*
* contextName.
*/
DEBUGDUMPHEADER("send", "contextName");
rc = asn_realloc_rbuild_string(pkt, pkt_len, offset, 1,
(u_char) (ASN_UNIVERSAL | ASN_PRIMITIVE
| ASN_OCTET_STR),
(u_char *) pdu->contextName,
pdu->contextNameLen);
DEBUGINDENTLESS();
if (rc == 0) {
return 0;
}
/*
* contextEngineID.
*/
DEBUGDUMPHEADER("send", "contextEngineID");
rc = asn_realloc_rbuild_string(pkt, pkt_len, offset, 1,
(u_char) (ASN_UNIVERSAL | ASN_PRIMITIVE
| ASN_OCTET_STR),
pdu->contextEngineID,
pdu->contextEngineIDLen);
DEBUGINDENTLESS();
if (rc == 0) {
return 0;
}
rc = asn_realloc_rbuild_sequence(pkt, pkt_len, offset, 1,
(u_char) (ASN_SEQUENCE |
ASN_CONSTRUCTOR),
*offset - start_offset + body_len);
return rc;
} /* end snmpv3_scopedPDU_header_realloc_rbuild() */
#endif /* NETSNMP_USE_REVERSE_ASNENCODING */
#ifdef NETSNMP_USE_REVERSE_ASNENCODING
/*
* returns 0 if success, -1 if fail, not 0 if SM build failure
*/
int
snmpv3_packet_realloc_rbuild(u_char ** pkt, size_t * pkt_len,
size_t * offset, netsnmp_session * session,
netsnmp_pdu *pdu, u_char * pdu_data,
size_t pdu_data_len)
{
u_char *scoped_pdu, *hdrbuf = NULL, *hdr = NULL;
size_t hdrbuf_len = SNMP_MAX_MSG_V3_HDRS, hdr_offset =
0, spdu_offset = 0;
size_t body_end_offset = *offset, body_len = 0;
struct snmp_secmod_def *sptr = NULL;
int rc = 0;
/*
* Build a scopedPDU structure into the packet buffer.
*/
DEBUGPRINTPDUTYPE("send", pdu->command);
if (pdu_data) {
while ((*pkt_len - *offset) < pdu_data_len) {
if (!asn_realloc(pkt, pkt_len)) {
return -1;
}
}
*offset += pdu_data_len;
memcpy(*pkt + *pkt_len - *offset, pdu_data, pdu_data_len);
} else {
rc = snmp_pdu_realloc_rbuild(pkt, pkt_len, offset, pdu);
if (rc == 0) {
return -1;
}
}
body_len = *offset - body_end_offset;
DEBUGDUMPSECTION("send", "ScopedPdu");
rc = snmpv3_scopedPDU_header_realloc_rbuild(pkt, pkt_len, offset,
pdu, body_len);
if (rc == 0) {
return -1;
}
spdu_offset = *offset;
DEBUGINDENTADD(-4); /* Return from Scoped PDU. */
if ((hdrbuf = (u_char *) malloc(hdrbuf_len)) == NULL) {
return -1;
}
rc = snmpv3_header_realloc_rbuild(&hdrbuf, &hdrbuf_len, &hdr_offset,
session, pdu);
if (rc == 0) {
SNMP_FREE(hdrbuf);
return -1;
}
hdr = hdrbuf + hdrbuf_len - hdr_offset;
scoped_pdu = *pkt + *pkt_len - spdu_offset;
/*
* Call the security module to possibly encrypt and authenticate the
* message---the entire message to transmitted on the wire is returned.
*/
sptr = find_sec_mod(pdu->securityModel);
DEBUGDUMPSECTION("send", "SM msgSecurityParameters");
if (sptr && sptr->encode_reverse) {
struct snmp_secmod_outgoing_params parms;
parms.msgProcModel = pdu->msgParseModel;
parms.globalData = hdr;
parms.globalDataLen = hdr_offset;
parms.maxMsgSize = SNMP_MAX_MSG_SIZE;
parms.secModel = pdu->securityModel;
parms.secEngineID = pdu->securityEngineID;
parms.secEngineIDLen = pdu->securityEngineIDLen;
parms.secName = pdu->securityName;
parms.secNameLen = pdu->securityNameLen;
parms.secLevel = pdu->securityLevel;
parms.scopedPdu = scoped_pdu;
parms.scopedPduLen = spdu_offset;
parms.secStateRef = pdu->securityStateRef;
parms.wholeMsg = pkt;
parms.wholeMsgLen = pkt_len;
parms.wholeMsgOffset = offset;
parms.session = session;
parms.pdu = pdu;
rc = (*sptr->encode_reverse) (&parms);
} else {
if (!sptr) {
snmp_log(LOG_ERR,
"no such security service available: %d\n",
pdu->securityModel);
} else if (!sptr->encode_reverse) {
snmp_log(LOG_ERR,
"security service %d doesn't support reverse encoding.\n",
pdu->securityModel);
}
rc = -1;
}
DEBUGINDENTLESS();
SNMP_FREE(hdrbuf);
return rc;
} /* end snmpv3_packet_realloc_rbuild() */
#endif /* NETSNMP_USE_REVERSE_ASNENCODING */
/*
* returns 0 if success, -1 if fail, not 0 if SM build failure
*/
int
snmpv3_packet_build(netsnmp_session * session, netsnmp_pdu *pdu,
u_char * packet, size_t * out_length,
u_char * pdu_data, size_t pdu_data_len)
{
u_char *global_data, *sec_params, *spdu_hdr_e;
size_t global_data_len, sec_params_len;
u_char spdu_buf[SNMP_MAX_MSG_SIZE];
size_t spdu_buf_len, spdu_len;
u_char *cp;
int result;
struct snmp_secmod_def *sptr;
global_data = packet;
/*
* build the headers for the packet, returned addr = start of secParams
*/
sec_params = snmpv3_header_build(session, pdu, global_data,
out_length, 0, NULL);
if (sec_params == NULL)
return -1;
global_data_len = sec_params - global_data;
sec_params_len = *out_length; /* length left in packet buf for sec_params */
/*
* build a scopedPDU structure into spdu_buf
*/
spdu_buf_len = sizeof(spdu_buf);
DEBUGDUMPSECTION("send", "ScopedPdu");
cp = snmpv3_scopedPDU_header_build(pdu, spdu_buf, &spdu_buf_len,
&spdu_hdr_e);
if (cp == NULL)
return -1;
/*
* build the PDU structure onto the end of spdu_buf
*/
DEBUGPRINTPDUTYPE("send", ((pdu_data) ? *pdu_data : 0x00));
if (pdu_data) {
if (cp + pdu_data_len > spdu_buf + sizeof(spdu_buf)) {
snmp_log(LOG_ERR, "%s: PDU too big (%" NETSNMP_PRIz "d > %" NETSNMP_PRIz "d)\n",
NETSNMP_FUNCTION, pdu_data_len, sizeof(spdu_buf));
return -1;
}
memcpy(cp, pdu_data, pdu_data_len);
cp += pdu_data_len;
} else {
cp = snmp_pdu_build(pdu, cp, &spdu_buf_len);
if (cp == NULL)
return -1;
}
DEBUGINDENTADD(-4); /* return from Scoped PDU */
/*
* re-encode the actual ASN.1 length of the scopedPdu
*/
spdu_len = cp - spdu_hdr_e; /* length of scopedPdu minus ASN.1 headers */
spdu_buf_len = sizeof(spdu_buf);
if (asn_build_sequence(spdu_buf, &spdu_buf_len,
(u_char) (ASN_SEQUENCE | ASN_CONSTRUCTOR),
spdu_len) == NULL)
return -1;
spdu_len = cp - spdu_buf; /* the length of the entire scopedPdu */
/*
* call the security module to possibly encrypt and authenticate the
* message - the entire message to transmitted on the wire is returned
*/
cp = NULL;
*out_length = sizeof(spdu_buf);
DEBUGDUMPSECTION("send", "SM msgSecurityParameters");
sptr = find_sec_mod(pdu->securityModel);
if (sptr && sptr->encode_forward) {
struct snmp_secmod_outgoing_params parms;
parms.msgProcModel = pdu->msgParseModel;
parms.globalData = global_data;
parms.globalDataLen = global_data_len;
parms.maxMsgSize = SNMP_MAX_MSG_SIZE;
parms.secModel = pdu->securityModel;
parms.secEngineID = pdu->securityEngineID;
parms.secEngineIDLen = pdu->securityEngineIDLen;
parms.secName = pdu->securityName;
parms.secNameLen = pdu->securityNameLen;
parms.secLevel = pdu->securityLevel;
parms.scopedPdu = spdu_buf;
parms.scopedPduLen = spdu_len;
parms.secStateRef = pdu->securityStateRef;
parms.secParams = sec_params;
parms.secParamsLen = &sec_params_len;
parms.wholeMsg = &cp;
parms.wholeMsgLen = out_length;
parms.session = session;
parms.pdu = pdu;
result = (*sptr->encode_forward) (&parms);
} else {
if (!sptr) {
snmp_log(LOG_ERR, "no such security service available: %d\n",
pdu->securityModel);
} else if (!sptr->encode_forward) {
snmp_log(LOG_ERR,
"security service %d doesn't support forward out encoding.\n",
pdu->securityModel);
}
result = -1;
}
DEBUGINDENTLESS();
return result;
} /* end snmpv3_packet_build() */
/*
* Takes a session and a pdu and serializes the ASN PDU into the area
* pointed to by *pkt. *pkt_len is the size of the data area available.
* Returns the length of the completed packet in *offset. If any errors
* occur, -1 is returned. If all goes well, 0 is returned.
*/
static int
_snmp_build(u_char ** pkt, size_t * pkt_len, size_t * offset,
netsnmp_session * session, netsnmp_pdu *pdu)
{
#if !defined(NETSNMP_DISABLE_SNMPV1) || !defined(NETSNMP_DISABLE_SNMPV2C)
u_char *h0e = NULL;
size_t start_offset = *offset;
long version;
int rc = 0;
size_t length;
#endif /* support for community based SNMP */
u_char *cp;
if (NETSNMP_RUNTIME_PROTOCOL_SKIP(pdu->version)) {
DEBUGMSGTL(("snmp_send", "build packet (version 0x%02x disabled)\n",
(u_int)pdu->version));
session->s_snmp_errno = SNMPERR_BAD_VERSION;
return -1;
}
session->s_snmp_errno = 0;
session->s_errno = 0;
#ifdef NETSNMP_USE_REVERSE_ASNENCODING
if ((pdu->flags & UCD_MSG_FLAG_BULK_TOOBIG) ||
(0 == netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID,
NETSNMP_DS_LIB_REVERSE_ENCODE))) {
pdu->flags |= UCD_MSG_FLAG_FORWARD_ENCODE;
}
#endif /* NETSNMP_USE_REVERSE_ASNENCODING */
if (pdu->version == SNMP_VERSION_3) {
return snmpv3_build(pkt, pkt_len, offset, session, pdu);
}
switch (pdu->command) {
case SNMP_MSG_RESPONSE:
netsnmp_assert(0 == (pdu->flags & UCD_MSG_FLAG_EXPECT_RESPONSE));
#ifndef NETSNMP_NOTIFY_ONLY
/* FALL THROUGH */
case SNMP_MSG_GET:
case SNMP_MSG_GETNEXT:
/* FALL THROUGH */
#endif /* ! NETSNMP_NOTIFY_ONLY */
#ifndef NETSNMP_NO_WRITE_SUPPORT
case SNMP_MSG_SET:
#endif /* !NETSNMP_NO_WRITE_SUPPORT */
/*
* all versions support these PDU types
*/
/*
* initialize defaulted PDU fields
*/
if (pdu->errstat == SNMP_DEFAULT_ERRSTAT)
pdu->errstat = 0;
if (pdu->errindex == SNMP_DEFAULT_ERRINDEX)
pdu->errindex = 0;
break;
case SNMP_MSG_TRAP2:
netsnmp_assert(0 == (pdu->flags & UCD_MSG_FLAG_EXPECT_RESPONSE));
/* FALL THROUGH */
case SNMP_MSG_INFORM:
#ifndef NETSNMP_DISABLE_SNMPV1
/*
* not supported in SNMPv1 and SNMPsec
*/
if (pdu->version == SNMP_VERSION_1) {
session->s_snmp_errno = SNMPERR_V2_IN_V1;
return -1;
}
#endif
if (pdu->errstat == SNMP_DEFAULT_ERRSTAT)
pdu->errstat = 0;
if (pdu->errindex == SNMP_DEFAULT_ERRINDEX)
pdu->errindex = 0;
break;
#ifndef NETSNMP_NOTIFY_ONLY
case SNMP_MSG_GETBULK:
/*
* not supported in SNMPv1 and SNMPsec
*/
#ifndef NETSNMP_DISABLE_SNMPV1
if (pdu->version == SNMP_VERSION_1) {
session->s_snmp_errno = SNMPERR_V2_IN_V1;
return -1;
}
#endif
if (pdu->max_repetitions < 0) {
session->s_snmp_errno = SNMPERR_BAD_REPETITIONS;
return -1;
}
if (pdu->non_repeaters < 0) {
session->s_snmp_errno = SNMPERR_BAD_REPEATERS;
return -1;
}
break;
#endif /* ! NETSNMP_NOTIFY_ONLY */
case SNMP_MSG_TRAP:
/*
* *only* supported in SNMPv1 and SNMPsec
*/
#ifndef NETSNMP_DISABLE_SNMPV1
if (pdu->version != SNMP_VERSION_1) {
session->s_snmp_errno = SNMPERR_V1_IN_V2;
return -1;
}
#endif
/*
* initialize defaulted Trap PDU fields
*/
pdu->reqid = 1; /* give a bogus non-error reqid for traps */
if (pdu->enterprise_length == SNMP_DEFAULT_ENTERPRISE_LENGTH) {
pdu->enterprise = (oid *) malloc(sizeof(DEFAULT_ENTERPRISE));
if (pdu->enterprise == NULL) {
session->s_snmp_errno = SNMPERR_MALLOC;
return -1;
}
memmove(pdu->enterprise, DEFAULT_ENTERPRISE,
sizeof(DEFAULT_ENTERPRISE));
pdu->enterprise_length =
sizeof(DEFAULT_ENTERPRISE) / sizeof(oid);
}
if (pdu->time == SNMP_DEFAULT_TIME)
pdu->time = DEFAULT_TIME;
/*
* don't expect a response
*/
pdu->flags &= (~UCD_MSG_FLAG_EXPECT_RESPONSE);
break;
case SNMP_MSG_REPORT: /* SNMPv3 only */
default:
session->s_snmp_errno = SNMPERR_UNKNOWN_PDU;
return -1;
}
/*
* save length
*/
#if !defined(NETSNMP_DISABLE_SNMPV1) || !defined(NETSNMP_DISABLE_SNMPV2C)
length = *pkt_len;
#endif
/*
* setup administrative fields based on version
*/
/*
* build the message wrapper and all the administrative fields
* upto the PDU sequence
* (note that actual length of message will be inserted later)
*/
switch (pdu->version) {
#ifndef NETSNMP_DISABLE_SNMPV1
case SNMP_VERSION_1:
#endif
#ifndef NETSNMP_DISABLE_SNMPV2C
case SNMP_VERSION_2c:
#endif
#if !defined(NETSNMP_DISABLE_SNMPV1) || !defined(NETSNMP_DISABLE_SNMPV2C)
#ifdef NETSNMP_NO_ZEROLENGTH_COMMUNITY
if (pdu->community_len == 0) {
if (session->community_len == 0) {
session->s_snmp_errno = SNMPERR_BAD_COMMUNITY;
return -1;
}
pdu->community = (u_char *) malloc(session->community_len);
if (pdu->community == NULL) {
session->s_snmp_errno = SNMPERR_MALLOC;
return -1;
}
memmove(pdu->community,
session->community, session->community_len);
pdu->community_len = session->community_len;
}
#else /* !NETSNMP_NO_ZEROLENGTH_COMMUNITY */
if (pdu->community_len == 0 && pdu->command != SNMP_MSG_RESPONSE) {
/*
* copy session community exactly to pdu community
*/
if (0 == session->community_len) {
SNMP_FREE(pdu->community);
} else if (pdu->community_len == session->community_len) {
memmove(pdu->community,
session->community, session->community_len);
} else {
SNMP_FREE(pdu->community);
pdu->community = (u_char *) malloc(session->community_len);
if (pdu->community == NULL) {
session->s_snmp_errno = SNMPERR_MALLOC;
return -1;
}
memmove(pdu->community,
session->community, session->community_len);
}
pdu->community_len = session->community_len;
}
#endif /* !NETSNMP_NO_ZEROLENGTH_COMMUNITY */
DEBUGMSGTL(("snmp_send", "Building SNMPv%ld message...\n",
(1 + pdu->version)));
#ifdef NETSNMP_USE_REVERSE_ASNENCODING
if (!(pdu->flags & UCD_MSG_FLAG_FORWARD_ENCODE)) {
DEBUGPRINTPDUTYPE("send", pdu->command);
rc = snmp_pdu_realloc_rbuild(pkt, pkt_len, offset, pdu);
if (rc == 0) {
return -1;
}
DEBUGDUMPHEADER("send", "Community String");
rc = asn_realloc_rbuild_string(pkt, pkt_len, offset, 1,
(u_char) (ASN_UNIVERSAL |
ASN_PRIMITIVE |
ASN_OCTET_STR),
pdu->community,
pdu->community_len);
DEBUGINDENTLESS();
if (rc == 0) {
return -1;
}
/*
* Store the version field.
*/
DEBUGDUMPHEADER("send", "SNMP Version Number");
version = pdu->version;
rc = asn_realloc_rbuild_int(pkt, pkt_len, offset, 1,
(u_char) (ASN_UNIVERSAL |
ASN_PRIMITIVE |
ASN_INTEGER),
(long *) &version,
sizeof(version));
DEBUGINDENTLESS();
if (rc == 0) {
return -1;
}
/*
* Build the final sequence.
*/
#ifndef NETSNMP_DISABLE_SNMPV1
if (pdu->version == SNMP_VERSION_1) {
DEBUGDUMPSECTION("send", "SNMPv1 Message");
} else {
#endif
DEBUGDUMPSECTION("send", "SNMPv2c Message");
#ifndef NETSNMP_DISABLE_SNMPV1
}
#endif
rc = asn_realloc_rbuild_sequence(pkt, pkt_len, offset, 1,
(u_char) (ASN_SEQUENCE |
ASN_CONSTRUCTOR),
*offset - start_offset);
DEBUGINDENTLESS();
if (rc == 0) {
return -1;
}
return 0;
} else {
#endif /* NETSNMP_USE_REVERSE_ASNENCODING */
/*
* Save current location and build SEQUENCE tag and length
* placeholder for SNMP message sequence
* (actual length will be inserted later)
*/
cp = asn_build_sequence(*pkt, pkt_len,
(u_char) (ASN_SEQUENCE |
ASN_CONSTRUCTOR), 0);
if (cp == NULL) {
return -1;
}
h0e = cp;
#ifndef NETSNMP_DISABLE_SNMPV1
if (pdu->version == SNMP_VERSION_1) {
DEBUGDUMPSECTION("send", "SNMPv1 Message");
} else {
#endif
DEBUGDUMPSECTION("send", "SNMPv2c Message");
#ifndef NETSNMP_DISABLE_SNMPV1
}
#endif
/*
* store the version field
*/
DEBUGDUMPHEADER("send", "SNMP Version Number");
version = pdu->version;
cp = asn_build_int(cp, pkt_len,
(u_char) (ASN_UNIVERSAL | ASN_PRIMITIVE |
ASN_INTEGER), (long *) &version,
sizeof(version));
DEBUGINDENTLESS();
if (cp == NULL)
return -1;
/*
* store the community string
*/
DEBUGDUMPHEADER("send", "Community String");
cp = asn_build_string(cp, pkt_len,
(u_char) (ASN_UNIVERSAL | ASN_PRIMITIVE |
ASN_OCTET_STR), pdu->community,
pdu->community_len);
DEBUGINDENTLESS();
if (cp == NULL)
return -1;
break;
#ifdef NETSNMP_USE_REVERSE_ASNENCODING
}
#endif /* NETSNMP_USE_REVERSE_ASNENCODING */
break;
#endif /* support for community based SNMP */
case SNMP_VERSION_2p:
case SNMP_VERSION_sec:
case SNMP_VERSION_2u:
case SNMP_VERSION_2star:
default:
session->s_snmp_errno = SNMPERR_BAD_VERSION;
return -1;
}
DEBUGPRINTPDUTYPE("send", pdu->command);
cp = snmp_pdu_build(pdu, cp, pkt_len);
DEBUGINDENTADD(-4); /* return from entire v1/v2c message */
if (cp == NULL)
return -1;
/*
* insert the actual length of the message sequence
*/
switch (pdu->version) {
#ifndef NETSNMP_DISABLE_SNMPV1
case SNMP_VERSION_1:
#endif
#ifndef NETSNMP_DISABLE_SNMPV2C
case SNMP_VERSION_2c:
#endif
#if !defined(NETSNMP_DISABLE_SNMPV1) || !defined(NETSNMP_DISABLE_SNMPV2C)
asn_build_sequence(*pkt, &length,
(u_char) (ASN_SEQUENCE | ASN_CONSTRUCTOR),
cp - h0e);
break;
#endif /* support for community based SNMP */
case SNMP_VERSION_2p:
case SNMP_VERSION_sec:
case SNMP_VERSION_2u:
case SNMP_VERSION_2star:
default:
session->s_snmp_errno = SNMPERR_BAD_VERSION;
return -1;
}
*pkt_len = cp - *pkt;
return 0;
}
/**
* Serialize a PDU into ASN format.
* @param pkt [out] Serialized PDU.
* @param pkt_len [out] Size of pkt.
* @param offset [out] Number of bytes written into *pkt.
* @param pss [in] Session pointer.
* @param pdu [in] PDU to serialize.
*
* @returns 0 upon success; -1 upon failure.
*/
int
snmp_build(u_char ** pkt, size_t * pkt_len, size_t * offset,
netsnmp_session * pss, netsnmp_pdu *pdu)
{
int rc;
rc = _snmp_build(pkt, pkt_len, offset, pss, pdu);
if (rc) {
if (!pss->s_snmp_errno) {
snmp_log(LOG_ERR, "snmp_build: unknown failure\n");
pss->s_snmp_errno = SNMPERR_BAD_ASN1_BUILD;
}
SET_SNMP_ERROR(pss->s_snmp_errno);
rc = -1;
}
return rc;
}
/*
* on error, returns NULL (likely an encoding problem).
*/
u_char *
snmp_pdu_build(netsnmp_pdu *pdu, u_char * cp, size_t * out_length)
{
u_char *h1, *h1e, *h2, *h2e, *save_ptr;
netsnmp_variable_list *vp, *save_vp = NULL;
size_t length, save_length;
length = *out_length;
/*
* Save current location and build PDU tag and length placeholder
* (actual length will be inserted later)
*/
h1 = cp;
cp = asn_build_sequence(cp, out_length, (u_char) pdu->command, 0);
if (cp == NULL)
return NULL;
h1e = cp;
/*
* store fields in the PDU preceding the variable-bindings sequence
*/
if (pdu->command != SNMP_MSG_TRAP) {
/*
* PDU is not an SNMPv1 trap
*/
DEBUGDUMPHEADER("send", "request_id");
/*
* request id
*/
cp = asn_build_int(cp, out_length,
(u_char) (ASN_UNIVERSAL | ASN_PRIMITIVE |
ASN_INTEGER), &pdu->reqid,
sizeof(pdu->reqid));
DEBUGINDENTLESS();
if (cp == NULL)
return NULL;
/*
* error status (getbulk non-repeaters)
*/
DEBUGDUMPHEADER("send", "error status");
cp = asn_build_int(cp, out_length,
(u_char) (ASN_UNIVERSAL | ASN_PRIMITIVE |
ASN_INTEGER), &pdu->errstat,
sizeof(pdu->errstat));
DEBUGINDENTLESS();
if (cp == NULL)
return NULL;
/*
* error index (getbulk max-repetitions)
*/
DEBUGDUMPHEADER("send", "error index");
cp = asn_build_int(cp, out_length,
(u_char) (ASN_UNIVERSAL | ASN_PRIMITIVE |
ASN_INTEGER), &pdu->errindex,
sizeof(pdu->errindex));
DEBUGINDENTLESS();
if (cp == NULL)
return NULL;
} else {
/*
* an SNMPv1 trap PDU
*/
/*
* enterprise
*/
DEBUGDUMPHEADER("send", "enterprise OBJID");
cp = asn_build_objid(cp, out_length,
(u_char) (ASN_UNIVERSAL | ASN_PRIMITIVE |
ASN_OBJECT_ID),
(oid *) pdu->enterprise,
pdu->enterprise_length);
DEBUGINDENTLESS();
if (cp == NULL)
return NULL;
/*
* agent-addr
*/
DEBUGDUMPHEADER("send", "agent Address");
cp = asn_build_string(cp, out_length,
(u_char) (ASN_IPADDRESS | ASN_PRIMITIVE),
(u_char *) pdu->agent_addr, 4);
DEBUGINDENTLESS();
if (cp == NULL)
return NULL;
/*
* generic trap
*/
DEBUGDUMPHEADER("send", "generic trap number");
cp = asn_build_int(cp, out_length,
(u_char) (ASN_UNIVERSAL | ASN_PRIMITIVE |
ASN_INTEGER),
(long *) &pdu->trap_type,
sizeof(pdu->trap_type));
DEBUGINDENTLESS();
if (cp == NULL)
return NULL;
/*
* specific trap
*/
DEBUGDUMPHEADER("send", "specific trap number");
cp = asn_build_int(cp, out_length,
(u_char) (ASN_UNIVERSAL | ASN_PRIMITIVE |
ASN_INTEGER),
(long *) &pdu->specific_type,
sizeof(pdu->specific_type));
DEBUGINDENTLESS();
if (cp == NULL)
return NULL;
/*
* timestamp
*/
DEBUGDUMPHEADER("send", "timestamp");
cp = asn_build_unsigned_int(cp, out_length,
(u_char) (ASN_TIMETICKS |
ASN_PRIMITIVE), &pdu->time,
sizeof(pdu->time));
DEBUGINDENTLESS();
if (cp == NULL)
return NULL;
}
/*
* Save current location and build SEQUENCE tag and length placeholder
* for variable-bindings sequence
* (actual length will be inserted later)
*/
h2 = cp;
cp = asn_build_sequence(cp, out_length,
(u_char) (ASN_SEQUENCE | ASN_CONSTRUCTOR), 0);
if (cp == NULL)
return NULL;
h2e = cp;
/*
* Store variable-bindings
*/
DEBUGDUMPSECTION("send", "VarBindList");
for (vp = pdu->variables; vp; vp = vp->next_variable) {
/*
* if estimated getbulk response size exceeded packet max size,
* processing was stopped before bulk cache was filled and type
* was set to ASN_PRIV_STOP, indicating that the rest of the varbinds
* in the cache are empty and we can stop encoding them.
*/
if (ASN_PRIV_STOP == vp->type)
break;
/*
* save current ptr and length so that if we exceed the packet length
* encoding this varbind and this is a bulk response, we can drop
* the failed varbind (and any that follow it) and continue encoding
* the (shorter) bulk response.
*/
save_ptr = cp;
save_length = *out_length;
DEBUGDUMPSECTION("send", "VarBind");
cp = snmp_build_var_op(cp, vp->name, &vp->name_length, vp->type,
vp->val_len, (u_char *) vp->val.string,
out_length);
DEBUGINDENTLESS();
if (cp == NULL) {
if (save_vp && (pdu->flags & UCD_MSG_FLAG_BULK_TOOBIG)) {
DEBUGDUMPSECTION("send",
"VarBind would exceed packet size; dropped");
cp = save_ptr;
*out_length = save_length;
break;
} else
return NULL;
}
save_vp = vp;
}
DEBUGINDENTLESS();
/** did we run out of room? (should only happen for bulk reponses) */
if (vp && save_vp) {
save_vp->next_variable = NULL; /* truncate variable list */
/** count remaining varbinds in list, then free them */
save_vp = vp;
for(save_length = 0; save_vp; save_vp = save_vp->next_variable)
++save_length;
DEBUGMSGTL(("send", "trimmed %" NETSNMP_PRIz "d variables\n", save_length));
snmp_free_varbind(vp);
}
/*
* insert actual length of variable-bindings sequence
*/
asn_build_sequence(h2, &length,
(u_char) (ASN_SEQUENCE | ASN_CONSTRUCTOR),
cp - h2e);
/*
* insert actual length of PDU sequence
*/
asn_build_sequence(h1, &length, (u_char) pdu->command, cp - h1e);
return cp;
}
#ifdef NETSNMP_USE_REVERSE_ASNENCODING
/*
* On error, returns 0 (likely an encoding problem).
*/
int
snmp_pdu_realloc_rbuild(u_char ** pkt, size_t * pkt_len, size_t * offset,
netsnmp_pdu *pdu)
{
#ifndef VPCACHE_SIZE
#define VPCACHE_SIZE 50
#endif
netsnmp_variable_list *vpcache[VPCACHE_SIZE];
netsnmp_variable_list *vp, *tmpvp;
size_t start_offset = *offset;
int i, wrapped = 0, notdone, final, rc = 0;
DEBUGMSGTL(("snmp_pdu_realloc_rbuild", "starting\n"));
for (vp = pdu->variables, i = VPCACHE_SIZE - 1; vp;
vp = vp->next_variable, i--) {
/*
* if estimated getbulk response size exceeded packet max size,
* processing was stopped before bulk cache was filled and type
* was set to ASN_PRIV_STOP, indicating that the rest of the varbinds
* in the cache are empty and we can stop encoding them.
*/
if (ASN_PRIV_STOP == vp->type)
break;
if (i < 0) {
wrapped = notdone = 1;
i = VPCACHE_SIZE - 1;
DEBUGMSGTL(("snmp_pdu_realloc_rbuild", "wrapped\n"));
}
vpcache[i] = vp;
}
final = i + 1;
do {
for (i = final; i < VPCACHE_SIZE; i++) {
vp = vpcache[i];
DEBUGDUMPSECTION("send", "VarBind");
rc = snmp_realloc_rbuild_var_op(pkt, pkt_len, offset, 1,
vp->name, &vp->name_length,
vp->type,
(u_char *) vp->val.string,
vp->val_len);
DEBUGINDENTLESS();
if (rc == 0) {
return 0;
}
}
DEBUGINDENTLESS();
if (wrapped) {
notdone = 1;
for (i = 0; i < final; i++) {
vp = vpcache[i];
DEBUGDUMPSECTION("send", "VarBind");
rc = snmp_realloc_rbuild_var_op(pkt, pkt_len, offset, 1,
vp->name, &vp->name_length,
vp->type,
(u_char *) vp->val.string,
vp->val_len);
DEBUGINDENTLESS();
if (rc == 0) {
return 0;
}
}
if (final == 0) {
tmpvp = vpcache[VPCACHE_SIZE - 1];
} else {
tmpvp = vpcache[final - 1];
}
wrapped = 0;
for (vp = pdu->variables, i = VPCACHE_SIZE - 1;
vp && vp != tmpvp; vp = vp->next_variable, i--) {
if (i < 0) {
wrapped = 1;
i = VPCACHE_SIZE - 1;
DEBUGMSGTL(("snmp_pdu_realloc_rbuild", "wrapped\n"));
}
vpcache[i] = vp;
}
final = i + 1;
} else {
notdone = 0;
}
} while (notdone);
/*
* Save current location and build SEQUENCE tag and length placeholder for
* variable-bindings sequence (actual length will be inserted later).
*/
rc = asn_realloc_rbuild_sequence(pkt, pkt_len, offset, 1,
(u_char) (ASN_SEQUENCE |
ASN_CONSTRUCTOR),
*offset - start_offset);
/*
* Store fields in the PDU preceding the variable-bindings sequence.
*/
if (pdu->command != SNMP_MSG_TRAP) {
/*
* Error index (getbulk max-repetitions).
*/
DEBUGDUMPHEADER("send", "error index");
rc = asn_realloc_rbuild_int(pkt, pkt_len, offset, 1,
(u_char) (ASN_UNIVERSAL | ASN_PRIMITIVE
| ASN_INTEGER),
&pdu->errindex, sizeof(pdu->errindex));
DEBUGINDENTLESS();
if (rc == 0) {
return 0;
}
/*
* Error status (getbulk non-repeaters).
*/
DEBUGDUMPHEADER("send", "error status");
rc = asn_realloc_rbuild_int(pkt, pkt_len, offset, 1,
(u_char) (ASN_UNIVERSAL | ASN_PRIMITIVE
| ASN_INTEGER),
&pdu->errstat, sizeof(pdu->errstat));
DEBUGINDENTLESS();
if (rc == 0) {
return 0;
}
/*
* Request ID.
*/
DEBUGDUMPHEADER("send", "request_id");
rc = asn_realloc_rbuild_int(pkt, pkt_len, offset, 1,
(u_char) (ASN_UNIVERSAL | ASN_PRIMITIVE
| ASN_INTEGER), &pdu->reqid,
sizeof(pdu->reqid));
DEBUGINDENTLESS();
if (rc == 0) {
return 0;
}
} else {
/*
* An SNMPv1 trap PDU.
*/
/*
* Timestamp.
*/
DEBUGDUMPHEADER("send", "timestamp");
rc = asn_realloc_rbuild_unsigned_int(pkt, pkt_len, offset, 1,
(u_char) (ASN_TIMETICKS |
ASN_PRIMITIVE),
&pdu->time,
sizeof(pdu->time));
DEBUGINDENTLESS();
if (rc == 0) {
return 0;
}
/*
* Specific trap.
*/
DEBUGDUMPHEADER("send", "specific trap number");
rc = asn_realloc_rbuild_int(pkt, pkt_len, offset, 1,
(u_char) (ASN_UNIVERSAL | ASN_PRIMITIVE
| ASN_INTEGER),
(long *) &pdu->specific_type,
sizeof(pdu->specific_type));
DEBUGINDENTLESS();
if (rc == 0) {
return 0;
}
/*
* Generic trap.
*/
DEBUGDUMPHEADER("send", "generic trap number");
rc = asn_realloc_rbuild_int(pkt, pkt_len, offset, 1,
(u_char) (ASN_UNIVERSAL | ASN_PRIMITIVE
| ASN_INTEGER),
(long *) &pdu->trap_type,
sizeof(pdu->trap_type));
DEBUGINDENTLESS();
if (rc == 0) {
return 0;
}
/*
* Agent-addr.
*/
DEBUGDUMPHEADER("send", "agent Address");
rc = asn_realloc_rbuild_string(pkt, pkt_len, offset, 1,
(u_char) (ASN_IPADDRESS |
ASN_PRIMITIVE),
(u_char *) pdu->agent_addr, 4);
DEBUGINDENTLESS();
if (rc == 0) {
return 0;
}
/*
* Enterprise.
*/
DEBUGDUMPHEADER("send", "enterprise OBJID");
rc = asn_realloc_rbuild_objid(pkt, pkt_len, offset, 1,
(u_char) (ASN_UNIVERSAL |
ASN_PRIMITIVE |
ASN_OBJECT_ID),
(oid *) pdu->enterprise,
pdu->enterprise_length);
DEBUGINDENTLESS();
if (rc == 0) {
return 0;
}
}
/*
* Build the PDU sequence.
*/
rc = asn_realloc_rbuild_sequence(pkt, pkt_len, offset, 1,
(u_char) pdu->command,
*offset - start_offset);
return rc;
}
#endif /* NETSNMP_USE_REVERSE_ASNENCODING */
/*
* Parses the packet received to determine version, either directly
* from packets version field or inferred from ASN.1 construct.
*/
static int
snmp_parse_version(u_char * data, size_t length)
{
u_char type;
long version = SNMPERR_BAD_VERSION;
data = asn_parse_sequence(data, &length, &type,
(ASN_SEQUENCE | ASN_CONSTRUCTOR), "version");
if (data) {
DEBUGDUMPHEADER("recv", "SNMP Version");
data =
asn_parse_int(data, &length, &type, &version, sizeof(version));
DEBUGINDENTLESS();
if (!data || type != ASN_INTEGER) {
return SNMPERR_BAD_VERSION;
}
}
return version;
}
int
snmpv3_parse(netsnmp_pdu *pdu,
u_char * data,
size_t * length,
u_char ** after_header, netsnmp_session * sess)
{
u_char type, msg_flags;
long ver, msg_sec_model;
size_t max_size_response;
u_char tmp_buf[SNMP_MAX_MSG_SIZE];
size_t tmp_buf_len;
u_char pdu_buf[SNMP_MAX_MSG_SIZE];
u_char *mallocbuf = NULL;
size_t pdu_buf_len = SNMP_MAX_MSG_SIZE;
u_char *sec_params;
u_char *msg_data;
u_char *cp;
size_t asn_len, msg_len;
int ret, ret_val;
struct snmp_secmod_def *sptr;
msg_data = data;
msg_len = *length;
/*
* message is an ASN.1 SEQUENCE
*/
DEBUGDUMPSECTION("recv", "SNMPv3 Message");
data = asn_parse_sequence(data, length, &type,
(ASN_SEQUENCE | ASN_CONSTRUCTOR), "message");
if (data == NULL) {
/*
* error msg detail is set
*/
snmp_increment_statistic(STAT_SNMPINASNPARSEERRS);
DEBUGINDENTLESS();
return SNMPERR_ASN_PARSE_ERR;
}
/*
* parse msgVersion
*/
DEBUGDUMPHEADER("recv", "SNMP Version Number");
data = asn_parse_int(data, length, &type, &ver, sizeof(ver));
DEBUGINDENTLESS();
if (data == NULL) {
ERROR_MSG("bad parse of version");
snmp_increment_statistic(STAT_SNMPINASNPARSEERRS);
DEBUGINDENTLESS();
return SNMPERR_ASN_PARSE_ERR;
}
pdu->version = ver;
/*
* parse msgGlobalData sequence
*/
cp = data;
asn_len = *length;
DEBUGDUMPSECTION("recv", "msgGlobalData");
data = asn_parse_sequence(data, &asn_len, &type,
(ASN_SEQUENCE | ASN_CONSTRUCTOR),
"msgGlobalData");
if (data == NULL) {
/*
* error msg detail is set
*/
snmp_increment_statistic(STAT_SNMPINASNPARSEERRS);
DEBUGINDENTADD(-4);
return SNMPERR_ASN_PARSE_ERR;
}
*length -= data - cp; /* subtract off the length of the header */
/*
* msgID
*/
DEBUGDUMPHEADER("recv", "msgID");
data =
asn_parse_int(data, length, &type, &pdu->msgid,
sizeof(pdu->msgid));
DEBUGINDENTLESS();
if (data == NULL || type != ASN_INTEGER) {
ERROR_MSG("error parsing msgID");
DEBUGINDENTADD(-4);
snmp_increment_statistic(STAT_SNMPINASNPARSEERRS);
return SNMPERR_ASN_PARSE_ERR;
}
/*
* Check the msgID we received is a legal value. If not, then increment
* snmpInASNParseErrs and return the appropriate error (see RFC 2572,
* para. 7.2, section 2 -- note that a bad msgID means that the received
* message is NOT a serialiization of an SNMPv3Message, since the msgID
* field is out of bounds).
*/
if (pdu->msgid < 0 || pdu->msgid > SNMP_MAX_PACKET_LEN) {
snmp_log(LOG_ERR, "Received bad msgID (%ld %s %s).\n", pdu->msgid,
(pdu->msgid < 0) ? "<" : ">",
(pdu->msgid < 0) ? "0" : "2^31 - 1");
snmp_increment_statistic(STAT_SNMPINASNPARSEERRS);
DEBUGINDENTADD(-4);
return SNMPERR_ASN_PARSE_ERR;
}
/*
* msgMaxSize
*/
DEBUGDUMPHEADER("recv:msgMaxSize", "msgMaxSize");
data = asn_parse_int(data, length, &type, &pdu->msgMaxSize,
sizeof(pdu->msgMaxSize));
DEBUGINDENTLESS();
if (data == NULL || type != ASN_INTEGER) {
ERROR_MSG("error parsing msgMaxSize");
snmp_increment_statistic(STAT_SNMPINASNPARSEERRS);
DEBUGINDENTADD(-4);
return SNMPERR_ASN_PARSE_ERR;
}
/*
* Check the msgMaxSize we received is a legal value. If not, then
* increment snmpInASNParseErrs and return the appropriate error (see RFC
* 2572, para. 7.2, section 2 -- note that a bad msgMaxSize means that the
* received message is NOT a serialiization of an SNMPv3Message, since the
* msgMaxSize field is out of bounds).
*/
if (pdu->msgMaxSize < SNMP_MIN_MAX_LEN) {
snmp_log(LOG_ERR, "Received bad msgMaxSize (%lu < 484).\n",
pdu->msgMaxSize);
snmp_increment_statistic(STAT_SNMPINASNPARSEERRS);
DEBUGINDENTADD(-4);
return SNMPERR_ASN_PARSE_ERR;
} else if (pdu->msgMaxSize > SNMP_MAX_PACKET_LEN) {
snmp_log(LOG_ERR, "Received bad msgMaxSize (%lu > 2^31 - 1).\n",
pdu->msgMaxSize);
snmp_increment_statistic(STAT_SNMPINASNPARSEERRS);
DEBUGINDENTADD(-4);
return SNMPERR_ASN_PARSE_ERR;
} else {
DEBUGMSGTL(("snmpv3_parse:msgMaxSize", "msgMaxSize %lu received\n",
pdu->msgMaxSize));
/** don't increase max msg size if we've already got one */
if (sess->sndMsgMaxSize < pdu->msgMaxSize) {
DEBUGMSGTL(("snmpv3_parse:msgMaxSize",
"msgMaxSize %" NETSNMP_PRIz "d greater than session max %ld; reducing\n",
sess->sndMsgMaxSize, pdu->msgMaxSize));
pdu->msgMaxSize = sess->sndMsgMaxSize;
}
}
/*
* msgFlags
*/
tmp_buf_len = SNMP_MAX_MSG_SIZE;
DEBUGDUMPHEADER("recv", "msgFlags");
data = asn_parse_string(data, length, &type, tmp_buf, &tmp_buf_len);
DEBUGINDENTLESS();
if (data == NULL || type != ASN_OCTET_STR || tmp_buf_len != 1) {
ERROR_MSG("error parsing msgFlags");
snmp_increment_statistic(STAT_SNMPINASNPARSEERRS);
DEBUGINDENTADD(-4);
return SNMPERR_ASN_PARSE_ERR;
}
msg_flags = *tmp_buf;
if (msg_flags & SNMP_MSG_FLAG_RPRT_BIT)
pdu->flags |= SNMP_MSG_FLAG_RPRT_BIT;
else
pdu->flags &= (~SNMP_MSG_FLAG_RPRT_BIT);
/*
* msgSecurityModel
*/
DEBUGDUMPHEADER("recv", "msgSecurityModel");
data = asn_parse_int(data, length, &type, &msg_sec_model,
sizeof(msg_sec_model));
DEBUGINDENTADD(-4); /* return from global data indent */
if (data == NULL || type != ASN_INTEGER ||
msg_sec_model < 1 || msg_sec_model > 0x7fffffff) {
ERROR_MSG("error parsing msgSecurityModel");
snmp_increment_statistic(STAT_SNMPINASNPARSEERRS);
DEBUGINDENTLESS();
return SNMPERR_ASN_PARSE_ERR;
}
sptr = find_sec_mod(msg_sec_model);
if (!sptr) {
snmp_log(LOG_WARNING, "unknown security model: %ld\n",
msg_sec_model);
snmp_increment_statistic(STAT_SNMPUNKNOWNSECURITYMODELS);
DEBUGINDENTLESS();
return SNMPERR_UNKNOWN_SEC_MODEL;
}
pdu->securityModel = msg_sec_model;
if (msg_flags & SNMP_MSG_FLAG_PRIV_BIT &&
!(msg_flags & SNMP_MSG_FLAG_AUTH_BIT)) {
ERROR_MSG("invalid message, illegal msgFlags");
snmp_increment_statistic(STAT_SNMPINVALIDMSGS);
DEBUGINDENTLESS();
return SNMPERR_INVALID_MSG;
}
pdu->securityLevel = ((msg_flags & SNMP_MSG_FLAG_AUTH_BIT)
? ((msg_flags & SNMP_MSG_FLAG_PRIV_BIT)
? SNMP_SEC_LEVEL_AUTHPRIV
: SNMP_SEC_LEVEL_AUTHNOPRIV)
: SNMP_SEC_LEVEL_NOAUTH);
/*
* end of msgGlobalData
*/
/*
* securtityParameters OCTET STRING begins after msgGlobalData
*/
sec_params = data;
pdu->contextEngineID = (u_char *) calloc(1, SNMP_MAX_ENG_SIZE);
pdu->contextEngineIDLen = SNMP_MAX_ENG_SIZE;
/*
* Note: there is no length limit on the msgAuthoritativeEngineID field,
* although we would EXPECT it to be limited to 32 (the SnmpEngineID TC
* limit). We'll use double that here to be on the safe side.
*/
pdu->securityEngineID = (u_char *) calloc(1, SNMP_MAX_ENG_SIZE * 2);
pdu->securityEngineIDLen = SNMP_MAX_ENG_SIZE * 2;
pdu->securityName = (char *) calloc(1, SNMP_MAX_SEC_NAME_SIZE);
pdu->securityNameLen = SNMP_MAX_SEC_NAME_SIZE;
if ((pdu->securityName == NULL) ||
(pdu->securityEngineID == NULL) ||
(pdu->contextEngineID == NULL)) {
return SNMPERR_MALLOC;
}
if (pdu_buf_len < msg_len
&& pdu->securityLevel == SNMP_SEC_LEVEL_AUTHPRIV) {
/*
* space needed is larger than we have in the default buffer
*/
mallocbuf = (u_char *) calloc(1, msg_len);
pdu_buf_len = msg_len;
cp = mallocbuf;
} else {
memset(pdu_buf, 0, pdu_buf_len);
cp = pdu_buf;
}
DEBUGDUMPSECTION("recv", "SM msgSecurityParameters");
if (sptr->decode) {
struct snmp_secmod_incoming_params parms;
parms.msgProcModel = pdu->msgParseModel;
parms.maxMsgSize = pdu->msgMaxSize;
parms.secParams = sec_params;
parms.secModel = msg_sec_model;
parms.secLevel = pdu->securityLevel;
parms.wholeMsg = msg_data;
parms.wholeMsgLen = msg_len;
parms.secEngineID = pdu->securityEngineID;
parms.secEngineIDLen = &pdu->securityEngineIDLen;
parms.secName = pdu->securityName;
parms.secNameLen = &pdu->securityNameLen;
parms.scopedPdu = &cp;
parms.scopedPduLen = &pdu_buf_len;
parms.maxSizeResponse = &max_size_response;
parms.secStateRef = &pdu->securityStateRef;
parms.sess = sess;
parms.pdu = pdu;
parms.msg_flags = msg_flags;
ret_val = (*sptr->decode) (&parms);
} else {
SNMP_FREE(mallocbuf);
DEBUGINDENTLESS();
snmp_log(LOG_WARNING, "security service %ld can't decode packets\n",
msg_sec_model);
return (-1);
}
if (ret_val != SNMPERR_SUCCESS) {
DEBUGDUMPSECTION("recv", "ScopedPDU");
/*
* Parse as much as possible -- though I don't see the point? [jbpn].
*/
if (cp) {
cp = snmpv3_scopedPDU_parse(pdu, cp, &pdu_buf_len);
}
if (cp) {
DEBUGPRINTPDUTYPE("recv", *cp);
snmp_pdu_parse(pdu, cp, &pdu_buf_len);
DEBUGINDENTADD(-8);
} else {
DEBUGINDENTADD(-4);
}
SNMP_FREE(mallocbuf);
return ret_val;
}
/*
* parse plaintext ScopedPDU sequence
*/
*length = pdu_buf_len;
DEBUGDUMPSECTION("recv", "ScopedPDU");
data = snmpv3_scopedPDU_parse(pdu, cp, length);
if (data == NULL) {
snmp_log(LOG_WARNING, "security service %ld error parsing ScopedPDU\n",
msg_sec_model);
ERROR_MSG("error parsing PDU");
snmp_increment_statistic(STAT_SNMPINASNPARSEERRS);
DEBUGINDENTADD(-4);
SNMP_FREE(mallocbuf);
return SNMPERR_ASN_PARSE_ERR;
}
/*
* parse the PDU.
*/
if (after_header != NULL) {
*after_header = data;
tmp_buf_len = *length;
}
DEBUGPRINTPDUTYPE("recv", *data);
ret = snmp_pdu_parse(pdu, data, length);
DEBUGINDENTADD(-8);
if (after_header != NULL) {
*length = tmp_buf_len;
}
if (ret != SNMPERR_SUCCESS) {
snmp_log(LOG_WARNING, "security service %ld error parsing ScopedPDU\n",
msg_sec_model);
ERROR_MSG("error parsing PDU");
snmp_increment_statistic(STAT_SNMPINASNPARSEERRS);
SNMP_FREE(mallocbuf);
return SNMPERR_ASN_PARSE_ERR;
}
SNMP_FREE(mallocbuf);
return SNMPERR_SUCCESS;
} /* end snmpv3_parse() */
static void
free_securityStateRef(netsnmp_pdu* pdu)
{
struct snmp_secmod_def *sptr;
if (!pdu->securityStateRef)
return;
sptr = find_sec_mod(pdu->securityModel);
if (sptr) {
if (sptr->pdu_free_state_ref) {
(*sptr->pdu_free_state_ref) (pdu->securityStateRef);
} else {
snmp_log(LOG_ERR,
"Security Model %d can't free state references\n",
pdu->securityModel);
}
} else {
snmp_log(LOG_ERR,
"Can't find security model to free ptr: %d\n",
pdu->securityModel);
}
pdu->securityStateRef = NULL;
}
#define ERROR_STAT_LENGTH 11
int
snmpv3_make_report(netsnmp_pdu *pdu, int error)
{
long ltmp;
static oid unknownSecurityLevel[] =
{ 1, 3, 6, 1, 6, 3, 15, 1, 1, 1, 0 };
static oid notInTimeWindow[] =
{ 1, 3, 6, 1, 6, 3, 15, 1, 1, 2, 0 };
static oid unknownUserName[] =
{ 1, 3, 6, 1, 6, 3, 15, 1, 1, 3, 0 };
static oid unknownEngineID[] =
{ 1, 3, 6, 1, 6, 3, 15, 1, 1, 4, 0 };
static oid wrongDigest[] = { 1, 3, 6, 1, 6, 3, 15, 1, 1, 5, 0 };
static oid decryptionError[] =
{ 1, 3, 6, 1, 6, 3, 15, 1, 1, 6, 0 };
oid *err_var;
int err_var_len;
#ifndef NETSNMP_FEATURE_REMOVE_STATISTICS
int stat_ind;
#endif
switch (error) {
case SNMPERR_USM_UNKNOWNENGINEID:
#ifndef NETSNMP_FEATURE_REMOVE_STATISTICS
stat_ind = STAT_USMSTATSUNKNOWNENGINEIDS;
#endif /* !NETSNMP_FEATURE_REMOVE_STATISTICS */
err_var = unknownEngineID;
err_var_len = ERROR_STAT_LENGTH;
break;
case SNMPERR_USM_UNKNOWNSECURITYNAME:
#ifndef NETSNMP_FEATURE_REMOVE_STATISTICS
stat_ind = STAT_USMSTATSUNKNOWNUSERNAMES;
#endif /* !NETSNMP_FEATURE_REMOVE_STATISTICS */
err_var = unknownUserName;
err_var_len = ERROR_STAT_LENGTH;
break;
case SNMPERR_USM_UNSUPPORTEDSECURITYLEVEL:
#ifndef NETSNMP_FEATURE_REMOVE_STATISTICS
stat_ind = STAT_USMSTATSUNSUPPORTEDSECLEVELS;
#endif /* !NETSNMP_FEATURE_REMOVE_STATISTICS */
err_var = unknownSecurityLevel;
err_var_len = ERROR_STAT_LENGTH;
break;
case SNMPERR_USM_AUTHENTICATIONFAILURE:
#ifndef NETSNMP_FEATURE_REMOVE_STATISTICS
stat_ind = STAT_USMSTATSWRONGDIGESTS;
#endif /* !NETSNMP_FEATURE_REMOVE_STATISTICS */
err_var = wrongDigest;
err_var_len = ERROR_STAT_LENGTH;
break;
case SNMPERR_USM_NOTINTIMEWINDOW:
#ifndef NETSNMP_FEATURE_REMOVE_STATISTICS
stat_ind = STAT_USMSTATSNOTINTIMEWINDOWS;
#endif /* !NETSNMP_FEATURE_REMOVE_STATISTICS */
err_var = notInTimeWindow;
err_var_len = ERROR_STAT_LENGTH;
break;
case SNMPERR_USM_DECRYPTIONERROR:
#ifndef NETSNMP_FEATURE_REMOVE_STATISTICS
stat_ind = STAT_USMSTATSDECRYPTIONERRORS;
#endif /* !NETSNMP_FEATURE_REMOVE_STATISTICS */
err_var = decryptionError;
err_var_len = ERROR_STAT_LENGTH;
break;
default:
return SNMPERR_GENERR;
}
snmp_free_varbind(pdu->variables); /* free the current varbind */
pdu->variables = NULL;
SNMP_FREE(pdu->securityEngineID);
pdu->securityEngineID =
snmpv3_generate_engineID(&pdu->securityEngineIDLen);
SNMP_FREE(pdu->contextEngineID);
pdu->contextEngineID =
snmpv3_generate_engineID(&pdu->contextEngineIDLen);
pdu->command = SNMP_MSG_REPORT;
pdu->errstat = 0;
pdu->errindex = 0;
SNMP_FREE(pdu->contextName);
pdu->contextName = strdup("");
pdu->contextNameLen = strlen(pdu->contextName);
/*
* reports shouldn't cache previous data.
*/
/*
* FIX - yes they should but USM needs to follow new EoP to determine
* which cached values to use
*/
free_securityStateRef(pdu);
if (error == SNMPERR_USM_NOTINTIMEWINDOW) {
pdu->securityLevel = SNMP_SEC_LEVEL_AUTHNOPRIV;
} else {
pdu->securityLevel = SNMP_SEC_LEVEL_NOAUTH;
}
/*
* find the appropriate error counter
*/
#ifndef NETSNMP_FEATURE_REMOVE_STATISTICS
ltmp = snmp_get_statistic(stat_ind);
#else /* !NETSNMP_FEATURE_REMOVE_STATISTICS */
ltmp = 1;
#endif /* !NETSNMP_FEATURE_REMOVE_STATISTICS */
/*
* return the appropriate error counter
*/
snmp_pdu_add_variable(pdu, err_var, err_var_len,
ASN_COUNTER, & ltmp, sizeof(ltmp));
return SNMPERR_SUCCESS;
} /* end snmpv3_make_report() */
int
snmpv3_get_report_type(netsnmp_pdu *pdu)
{
static oid snmpMPDStats[] = { 1, 3, 6, 1, 6, 3, 11, 2, 1 };
static oid targetStats[] = { 1, 3, 6, 1, 6, 3, 12, 1 };
static oid usmStats[] = { 1, 3, 6, 1, 6, 3, 15, 1, 1 };
netsnmp_variable_list *vp;
int rpt_type = SNMPERR_UNKNOWN_REPORT;
if (pdu == NULL || pdu->variables == NULL)
return rpt_type;
vp = pdu->variables;
/* MPD or USM based report statistics objects have the same length prefix
* so the actual statistics OID will have this length,
* plus one subidentifier for the scalar MIB object itself,
* and one for the instance subidentifier
*/
if (vp->name_length == REPORT_STATS_LEN + 2) {
if (memcmp(snmpMPDStats, vp->name, REPORT_STATS_LEN * sizeof(oid)) == 0) {
switch (vp->name[REPORT_STATS_LEN]) {
case REPORT_snmpUnknownSecurityModels_NUM:
rpt_type = SNMPERR_UNKNOWN_SEC_MODEL;
break;
case REPORT_snmpInvalidMsgs_NUM:
rpt_type = SNMPERR_INVALID_MSG;
break;
case REPORT_snmpUnknownPDUHandlers_NUM:
rpt_type = SNMPERR_BAD_VERSION;
break;
}
} else if (memcmp(usmStats, vp->name, REPORT_STATS_LEN * sizeof(oid)) == 0) {
switch (vp->name[REPORT_STATS_LEN]) {
case REPORT_usmStatsUnsupportedSecLevels_NUM:
rpt_type = SNMPERR_UNSUPPORTED_SEC_LEVEL;
break;
case REPORT_usmStatsNotInTimeWindows_NUM:
rpt_type = SNMPERR_NOT_IN_TIME_WINDOW;
break;
case REPORT_usmStatsUnknownUserNames_NUM:
rpt_type = SNMPERR_UNKNOWN_USER_NAME;
break;
case REPORT_usmStatsUnknownEngineIDs_NUM:
rpt_type = SNMPERR_UNKNOWN_ENG_ID;
break;
case REPORT_usmStatsWrongDigests_NUM:
rpt_type = SNMPERR_AUTHENTICATION_FAILURE;
break;
case REPORT_usmStatsDecryptionErrors_NUM:
rpt_type = SNMPERR_DECRYPTION_ERR;
break;
}
}
}
/* Context-based report statistics from the Target MIB are similar
* but the OID prefix has a different length
*/
if (vp->name_length == REPORT_STATS_LEN2 + 2) {
if (memcmp(targetStats, vp->name, REPORT_STATS_LEN2 * sizeof(oid)) == 0) {
switch (vp->name[REPORT_STATS_LEN2]) {
case REPORT_snmpUnavailableContexts_NUM:
rpt_type = SNMPERR_BAD_CONTEXT;
break;
case REPORT_snmpUnknownContexts_NUM:
rpt_type = SNMPERR_BAD_CONTEXT;
break;
}
}
}
DEBUGMSGTL(("report", "Report type: %d\n", rpt_type));
return rpt_type;
}
/*
* Parses the packet received on the input session, and places the data into
* the input pdu. length is the length of the input packet.
* If any errors are encountered, -1 or USM error is returned.
* Otherwise, a 0 is returned.
*/
static int
_snmp_parse(void *sessp,
netsnmp_session * session,
netsnmp_pdu *pdu, u_char * data, size_t length)
{
#if !defined(NETSNMP_DISABLE_SNMPV1) || !defined(NETSNMP_DISABLE_SNMPV2C)
u_char community[COMMUNITY_MAX_LEN];
size_t community_length = COMMUNITY_MAX_LEN;
#endif
int result = -1;
static oid snmpEngineIDoid[] = { 1,3,6,1,6,3,10,2,1,1,0};
static size_t snmpEngineIDoid_len = 11;
static char ourEngineID[SNMP_SEC_PARAM_BUF_SIZE];
static size_t ourEngineID_len = sizeof(ourEngineID);
netsnmp_pdu *pdu2 = NULL;
session->s_snmp_errno = 0;
session->s_errno = 0;
/*
* Ensure all incoming PDUs have a unique means of identification
* (This is not restricted to AgentX handling,
* though that is where the need becomes visible)
*/
pdu->transid = snmp_get_next_transid();
if (session->version != SNMP_DEFAULT_VERSION) {
pdu->version = session->version;
} else {
pdu->version = snmp_parse_version(data, length);
}
switch (pdu->version) {
#if !defined(NETSNMP_DISABLE_SNMPV1) || !defined(NETSNMP_DISABLE_SNMPV2C)
#ifndef NETSNMP_DISABLE_SNMPV1
case SNMP_VERSION_1:
#endif
#ifndef NETSNMP_DISABLE_SNMPV2C
case SNMP_VERSION_2c:
#endif
NETSNMP_RUNTIME_PROTOCOL_CHECK_V1V2(pdu->version,unsupported_version);
DEBUGMSGTL(("snmp_api", "Parsing SNMPv%ld message...\n",
(1 + pdu->version)));
/*
* authenticates message and returns length if valid
*/
#ifndef NETSNMP_DISABLE_SNMPV1
if (pdu->version == SNMP_VERSION_1) {
DEBUGDUMPSECTION("recv", "SNMPv1 message\n");
} else {
#endif
DEBUGDUMPSECTION("recv", "SNMPv2c message\n");
#ifndef NETSNMP_DISABLE_SNMPV1
}
#endif
data = snmp_comstr_parse(data, &length,
community, &community_length,
&pdu->version);
if (data == NULL)
return -1;
if (pdu->version != session->version &&
session->version != SNMP_DEFAULT_VERSION) {
session->s_snmp_errno = SNMPERR_BAD_VERSION;
return -1;
}
/*
* maybe get the community string.
*/
pdu->securityLevel = SNMP_SEC_LEVEL_NOAUTH;
pdu->securityModel =
#ifndef NETSNMP_DISABLE_SNMPV1
(pdu->version == SNMP_VERSION_1) ? SNMP_SEC_MODEL_SNMPv1 :
#endif
SNMP_SEC_MODEL_SNMPv2c;
SNMP_FREE(pdu->community);
pdu->community_len = 0;
pdu->community = (u_char *) 0;
if (community_length) {
pdu->community_len = community_length;
pdu->community = (u_char *) malloc(community_length);
if (pdu->community == NULL) {
session->s_snmp_errno = SNMPERR_MALLOC;
return -1;
}
memmove(pdu->community, community, community_length);
}
if (session->authenticator) {
data = session->authenticator(data, &length,
community, community_length);
if (data == NULL) {
session->s_snmp_errno = SNMPERR_AUTHENTICATION_FAILURE;
return -1;
}
}
DEBUGDUMPSECTION("recv", "PDU");
result = snmp_pdu_parse(pdu, data, &length);
if (result < 0) {
/*
* This indicates a parse error.
*/
snmp_increment_statistic(STAT_SNMPINASNPARSEERRS);
}
DEBUGINDENTADD(-6);
break;
#endif /* support for community based SNMP */
case SNMP_VERSION_3:
NETSNMP_RUNTIME_PROTOCOL_CHECK_V3(SNMP_VERSION_3,unsupported_version);
result = snmpv3_parse(pdu, data, &length, NULL, session);
DEBUGMSGTL(("snmp_parse",
"Parsed SNMPv3 message (secName:%s, secLevel:%s): %s\n",
pdu->securityName, secLevelName[pdu->securityLevel],
snmp_api_errstring(result)));
if (result) {
struct snmp_secmod_def *secmod =
find_sec_mod(pdu->securityModel);
if (!sessp) {
session->s_snmp_errno = result;
} else {
/*
* Call the security model to special handle any errors
*/
if (secmod && secmod->handle_report) {
struct session_list *slp = (struct session_list *) sessp;
(*secmod->handle_report)(sessp, slp->transport, session,
result, pdu);
}
}
free_securityStateRef(pdu);
}
/* Implement RFC5343 here for two reasons:
1) From a security perspective it handles this otherwise
always approved request earlier. It bypasses the need
for authorization to the snmpEngineID scalar, which is
what is what RFC3415 appendix A species as ok. Note
that we haven't bypassed authentication since if there
was an authentication eror it would have been handled
above in the if(result) part at the lastet.
2) From an application point of view if we let this request
get all the way to the application, it'd require that
all application types supporting discovery also fire up
a minimal agent in order to handle just this request
which seems like overkill. Though there is no other
application types that currently need discovery (NRs
accept notifications from contextEngineIDs that derive
from the NO not the NR). Also a lame excuse for doing
it here.
3) Less important technically, but the net-snmp agent
doesn't currently handle registrations of different
engineIDs either and it would have been a lot more work
to implement there since we'd need to support that
first. :-/ Supporting multiple context engineIDs should
be done anyway, so it's not a valid excuse here.
4) There is a lot less to do if we trump the agent at this
point; IE, the agent does a lot more unnecessary
processing when the only thing that should ever be in
this context by definition is the single scalar.
*/
/* special RFC5343 engineID discovery engineID check */
if (!netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID,
NETSNMP_DS_LIB_NO_DISCOVERY) &&
SNMP_MSG_RESPONSE != pdu->command &&
NULL != pdu->contextEngineID &&
pdu->contextEngineIDLen == 5 &&
pdu->contextEngineID[0] == 0x80 &&
pdu->contextEngineID[1] == 0x00 &&
pdu->contextEngineID[2] == 0x00 &&
pdu->contextEngineID[3] == 0x00 &&
pdu->contextEngineID[4] == 0x06) {
/* define a result so it doesn't get past us at this point
and gets dropped by future parts of the stack */
result = SNMPERR_JUST_A_CONTEXT_PROBE;
DEBUGMSGTL(("snmpv3_contextid", "starting context ID discovery\n"));
/* ensure exactly one variable */
if (NULL != pdu->variables &&
NULL == pdu->variables->next_variable &&
/* if it's a GET, match it exactly */
((SNMP_MSG_GET == pdu->command &&
snmp_oid_compare(snmpEngineIDoid,
snmpEngineIDoid_len,
pdu->variables->name,
pdu->variables->name_length) == 0)
/* if it's a GETNEXT ensure it's less than the engineID oid */
||
(SNMP_MSG_GETNEXT == pdu->command &&
snmp_oid_compare(snmpEngineIDoid,
snmpEngineIDoid_len,
pdu->variables->name,
pdu->variables->name_length) > 0)
)) {
DEBUGMSGTL(("snmpv3_contextid",
" One correct variable found\n"));
/* Note: we're explictly not handling a GETBULK. Deal. */
/* set up the response */
pdu2 = snmp_clone_pdu(pdu);
/* free the current varbind */
snmp_free_varbind(pdu2->variables);
/* set the variables */
pdu2->variables = NULL;
pdu2->command = SNMP_MSG_RESPONSE;
pdu2->errstat = 0;
pdu2->errindex = 0;
ourEngineID_len =
snmpv3_get_engineID((u_char*)ourEngineID, ourEngineID_len);
if (0 != ourEngineID_len) {
DEBUGMSGTL(("snmpv3_contextid",
" responding with our engineID\n"));
snmp_pdu_add_variable(pdu2,
snmpEngineIDoid, snmpEngineIDoid_len,
ASN_OCTET_STR,
ourEngineID, ourEngineID_len);
/* send the response */
if (0 == snmp_sess_send(sessp, pdu2)) {
DEBUGMSGTL(("snmpv3_contextid",
" sent it off!\n"));
snmp_free_pdu(pdu2);
snmp_log(LOG_ERR, "sending a response to the context engineID probe failed\n");
}
} else {
snmp_log(LOG_ERR, "failed to get our own engineID!\n");
}
} else {
snmp_log(LOG_WARNING,
"received an odd context engineID probe\n");
}
}
break;
case SNMPERR_BAD_VERSION:
ERROR_MSG("error parsing snmp message version");
snmp_increment_statistic(STAT_SNMPINASNPARSEERRS);
session->s_snmp_errno = SNMPERR_BAD_VERSION;
break;
unsupported_version: /* goto label */
case SNMP_VERSION_sec:
case SNMP_VERSION_2u:
case SNMP_VERSION_2star:
case SNMP_VERSION_2p:
default:
ERROR_MSG("unsupported snmp message version");
snmp_increment_statistic(STAT_SNMPINBADVERSIONS);
/*
* need better way to determine OS independent
* INT32_MAX value, for now hardcode
*/
if (pdu->version < 0 || pdu->version > 2147483647) {
snmp_increment_statistic(STAT_SNMPINASNPARSEERRS);
}
session->s_snmp_errno = SNMPERR_BAD_VERSION;
break;
}
return result;
}
/**
* Parse a PDU.
* @param slp [in] Session pointer (struct session_list).
* @param pss [in] Session pointer (netsnmp_session).
* @param pdu [out] Parsed PDU.
* @param data [in] PDU to parse.
* @param length [in] Length of data.
*
* @returns 0 upon success; -1 upon failure.
*/
int
snmp_parse(struct session_list *slp,
netsnmp_session * pss,
netsnmp_pdu *pdu, u_char * data, size_t length)
{
int rc;
rc = _snmp_parse(slp, pss, pdu, data, length);
if (rc) {
if (!pss->s_snmp_errno) {
pss->s_snmp_errno = SNMPERR_BAD_PARSE;
}
SET_SNMP_ERROR(pss->s_snmp_errno);
}
return rc;
}
int
snmp_pdu_parse(netsnmp_pdu *pdu, u_char * data, size_t * length)
{
u_char type;
u_char msg_type;
u_char *var_val;
size_t len;
size_t four;
netsnmp_variable_list *vp = NULL, *vplast = NULL;
oid objid[MAX_OID_LEN];
u_char *p;
/*
* Get the PDU type
*/
data = asn_parse_header(data, length, &msg_type);
if (data == NULL)
return -1;
DEBUGMSGTL(("dumpv_recv"," Command %s\n", snmp_pdu_type(msg_type)));
pdu->command = msg_type;
pdu->flags &= (~UCD_MSG_FLAG_RESPONSE_PDU);
/*
* get the fields in the PDU preceding the variable-bindings sequence
*/
switch (pdu->command) {
case SNMP_MSG_TRAP:
/*
* enterprise
*/
pdu->enterprise_length = MAX_OID_LEN;
data = asn_parse_objid(data, length, &type, objid,
&pdu->enterprise_length);
if (data == NULL)
return -1;
pdu->enterprise =
(oid *) malloc(pdu->enterprise_length * sizeof(oid));
if (pdu->enterprise == NULL) {
return -1;
}
memmove(pdu->enterprise, objid,
pdu->enterprise_length * sizeof(oid));
/*
* agent-addr
*/
four = 4;
data = asn_parse_string(data, length, &type,
(u_char *) pdu->agent_addr, &four);
if (data == NULL)
return -1;
/*
* generic trap
*/
data = asn_parse_int(data, length, &type, (long *) &pdu->trap_type,
sizeof(pdu->trap_type));
if (data == NULL)
return -1;
/*
* specific trap
*/
data =
asn_parse_int(data, length, &type,
(long *) &pdu->specific_type,
sizeof(pdu->specific_type));
if (data == NULL)
return -1;
/*
* timestamp
*/
data = asn_parse_unsigned_int(data, length, &type, &pdu->time,
sizeof(pdu->time));
if (data == NULL)
return -1;
break;
case SNMP_MSG_RESPONSE:
case SNMP_MSG_REPORT:
pdu->flags |= UCD_MSG_FLAG_RESPONSE_PDU;
/* FALL THROUGH */
case SNMP_MSG_TRAP2:
case SNMP_MSG_INFORM:
#ifndef NETSNMP_NOTIFY_ONLY
case SNMP_MSG_GET:
case SNMP_MSG_GETNEXT:
case SNMP_MSG_GETBULK:
#endif /* ! NETSNMP_NOTIFY_ONLY */
#ifndef NETSNMP_NO_WRITE_SUPPORT
case SNMP_MSG_SET:
#endif /* !NETSNMP_NO_WRITE_SUPPORT */
/*
* PDU is not an SNMPv1 TRAP
*/
/*
* request id
*/
DEBUGDUMPHEADER("recv", "request_id");
data = asn_parse_int(data, length, &type, &pdu->reqid,
sizeof(pdu->reqid));
DEBUGINDENTLESS();
if (data == NULL) {
return -1;
}
/*
* error status (getbulk non-repeaters)
*/
DEBUGDUMPHEADER("recv", "error status");
data = asn_parse_int(data, length, &type, &pdu->errstat,
sizeof(pdu->errstat));
DEBUGINDENTLESS();
if (data == NULL) {
return -1;
}
/*
* error index (getbulk max-repetitions)
*/
DEBUGDUMPHEADER("recv", "error index");
data = asn_parse_int(data, length, &type, &pdu->errindex,
sizeof(pdu->errindex));
DEBUGINDENTLESS();
if (data == NULL) {
return -1;
}
break;
default:
snmp_log(LOG_ERR, "Bad PDU type received: 0x%.2x\n", pdu->command);
snmp_increment_statistic(STAT_SNMPINASNPARSEERRS);
return -1;
}
/*
* get header for variable-bindings sequence
*/
DEBUGDUMPSECTION("recv", "VarBindList");
data = asn_parse_sequence(data, length, &type,
(ASN_SEQUENCE | ASN_CONSTRUCTOR),
"varbinds");
if (data == NULL)
goto fail;
/*
* get each varBind sequence
*/
while ((int) *length > 0) {
vp = SNMP_MALLOC_TYPEDEF(netsnmp_variable_list);
if (NULL == vp)
goto fail;
vp->name_length = MAX_OID_LEN;
DEBUGDUMPSECTION("recv", "VarBind");
data = snmp_parse_var_op(data, objid, &vp->name_length, &vp->type,
&vp->val_len, &var_val, length);
if (data == NULL)
goto fail;
if (snmp_set_var_objid(vp, objid, vp->name_length))
goto fail;
len = SNMP_MAX_PACKET_LEN;
DEBUGDUMPHEADER("recv", "Value");
switch ((short) vp->type) {
case ASN_INTEGER:
vp->val.integer = (long *) vp->buf;
vp->val_len = sizeof(long);
p = asn_parse_int(var_val, &len, &vp->type,
(long *) vp->val.integer,
sizeof(*vp->val.integer));
if (!p)
goto fail;
break;
case ASN_COUNTER:
case ASN_GAUGE:
case ASN_TIMETICKS:
case ASN_UINTEGER:
vp->val.integer = (long *) vp->buf;
vp->val_len = sizeof(u_long);
p = asn_parse_unsigned_int(var_val, &len, &vp->type,
(u_long *) vp->val.integer,
vp->val_len);
if (!p)
goto fail;
break;
#ifdef NETSNMP_WITH_OPAQUE_SPECIAL_TYPES
case ASN_OPAQUE_COUNTER64:
case ASN_OPAQUE_U64:
#endif /* NETSNMP_WITH_OPAQUE_SPECIAL_TYPES */
case ASN_COUNTER64:
vp->val.counter64 = (struct counter64 *) vp->buf;
vp->val_len = sizeof(struct counter64);
p = asn_parse_unsigned_int64(var_val, &len, &vp->type,
(struct counter64 *) vp->val.
counter64, vp->val_len);
if (!p)
goto fail;
break;
#ifdef NETSNMP_WITH_OPAQUE_SPECIAL_TYPES
case ASN_OPAQUE_FLOAT:
vp->val.floatVal = (float *) vp->buf;
vp->val_len = sizeof(float);
p = asn_parse_float(var_val, &len, &vp->type,
vp->val.floatVal, vp->val_len);
if (!p)
goto fail;
break;
case ASN_OPAQUE_DOUBLE:
vp->val.doubleVal = (double *) vp->buf;
vp->val_len = sizeof(double);
p = asn_parse_double(var_val, &len, &vp->type,
vp->val.doubleVal, vp->val_len);
if (!p)
goto fail;
break;
case ASN_OPAQUE_I64:
vp->val.counter64 = (struct counter64 *) vp->buf;
vp->val_len = sizeof(struct counter64);
p = asn_parse_signed_int64(var_val, &len, &vp->type,
(struct counter64 *) vp->val.counter64,
sizeof(*vp->val.counter64));
if (!p)
goto fail;
break;
#endif /* NETSNMP_WITH_OPAQUE_SPECIAL_TYPES */
case ASN_IPADDRESS:
if (vp->val_len != 4)
goto fail;
/* fallthrough */
case ASN_OCTET_STR:
case ASN_OPAQUE:
case ASN_NSAP:
if (vp->val_len < sizeof(vp->buf)) {
vp->val.string = (u_char *) vp->buf;
} else {
vp->val.string = (u_char *) malloc(vp->val_len);
}
if (vp->val.string == NULL) {
goto fail;
}
p = asn_parse_string(var_val, &len, &vp->type, vp->val.string,
&vp->val_len);
if (!p)
goto fail;
break;
case ASN_OBJECT_ID:
vp->val_len = MAX_OID_LEN;
p = asn_parse_objid(var_val, &len, &vp->type, objid, &vp->val_len);
if (!p)
goto fail;
vp->val_len *= sizeof(oid);
vp->val.objid = (oid *) malloc(vp->val_len);
if (vp->val.objid == NULL) {
goto fail;
}
memmove(vp->val.objid, objid, vp->val_len);
break;
case SNMP_NOSUCHOBJECT:
case SNMP_NOSUCHINSTANCE:
case SNMP_ENDOFMIBVIEW:
case ASN_NULL:
break;
case ASN_BIT_STR:
vp->val.bitstring = (u_char *) malloc(vp->val_len);
if (vp->val.bitstring == NULL) {
goto fail;
}
p = asn_parse_bitstring(var_val, &len, &vp->type,
vp->val.bitstring, &vp->val_len);
if (!p)
goto fail;
break;
default:
snmp_log(LOG_ERR, "bad type returned (%x)\n", vp->type);
goto fail;
break;
}
DEBUGINDENTADD(-4);
if (NULL == vplast) {
pdu->variables = vp;
} else {
vplast->next_variable = vp;
}
vplast = vp;
vp = NULL;
}
return 0;
fail:
{
const char *errstr = snmp_api_errstring(SNMPERR_SUCCESS);
DEBUGMSGTL(("recv", "error while parsing VarBindList:%s\n", errstr));
}
/** if we were parsing a var, remove it from the pdu and free it */
if (vp)
snmp_free_var(vp);
return -1;
}
/*
* snmp v3 utility function to parse into the scopedPdu. stores contextName
* and contextEngineID in pdu struct. Also stores pdu->command (handy for
* Report generation).
*
* returns pointer to begining of PDU or NULL on error.
*/
u_char *
snmpv3_scopedPDU_parse(netsnmp_pdu *pdu, u_char * cp, size_t * length)
{
u_char tmp_buf[SNMP_MAX_MSG_SIZE];
size_t tmp_buf_len;
u_char type;
size_t asn_len;
u_char *data;
pdu->command = 0; /* initialize so we know if it got parsed */
asn_len = *length;
data = asn_parse_sequence(cp, &asn_len, &type,
(ASN_SEQUENCE | ASN_CONSTRUCTOR),
"plaintext scopedPDU");
if (data == NULL) {
return NULL;
}
*length -= data - cp;
/*
* contextEngineID from scopedPdu
*/
DEBUGDUMPHEADER("recv", "contextEngineID");
data = asn_parse_string(data, length, &type, pdu->contextEngineID,
&pdu->contextEngineIDLen);
DEBUGINDENTLESS();
if (data == NULL) {
ERROR_MSG("error parsing contextEngineID from scopedPdu");
return NULL;
}
/*
* parse contextName from scopedPdu
*/
tmp_buf_len = SNMP_MAX_CONTEXT_SIZE;
DEBUGDUMPHEADER("recv", "contextName");
data = asn_parse_string(data, length, &type, tmp_buf, &tmp_buf_len);
DEBUGINDENTLESS();
if (data == NULL) {
ERROR_MSG("error parsing contextName from scopedPdu");
return NULL;
}
if (tmp_buf_len) {
pdu->contextName = (char *) malloc(tmp_buf_len);
memmove(pdu->contextName, tmp_buf, tmp_buf_len);
pdu->contextNameLen = tmp_buf_len;
} else {
pdu->contextName = strdup("");
pdu->contextNameLen = 0;
}
if (pdu->contextName == NULL) {
ERROR_MSG("error copying contextName from scopedPdu");
return NULL;
}
/*
* Get the PDU type
*/
asn_len = *length;
cp = asn_parse_header(data, &asn_len, &type);
if (cp == NULL)
return NULL;
pdu->command = type;
return data;
}
/* ===========================================================================
*
* build pdu packet
*/
int
netsnmp_build_packet(struct snmp_internal_session *isp, netsnmp_session *sp,
netsnmp_pdu *pdu, u_char **pktbuf_p,
size_t *pktbuf_len_p, u_char **pkt_p, size_t *len_p)
{
size_t offset = 0;
int result;
if (isp && isp->hook_realloc_build) {
result = isp->hook_realloc_build(sp, pdu, pktbuf_p, pktbuf_len_p,
&offset);
*pkt_p = *pktbuf_p;
*len_p = offset;
} else if (isp && isp->hook_build) {
*pkt_p = *pktbuf_p;
*len_p = *pktbuf_len_p;
result = isp->hook_build(sp, pdu, *pktbuf_p, len_p);
} else {
#ifdef NETSNMP_USE_REVERSE_ASNENCODING
if (!(pdu->flags & UCD_MSG_FLAG_FORWARD_ENCODE)) {
result = snmp_build(pktbuf_p, pktbuf_len_p, &offset, sp, pdu);
*pkt_p = *pktbuf_p + *pktbuf_len_p - offset;
*len_p = offset;
} else {
#endif
*pkt_p = *pktbuf_p;
*len_p = *pktbuf_len_p;
result = snmp_build(pktbuf_p, len_p, &offset, sp, pdu);
#ifdef NETSNMP_USE_REVERSE_ASNENCODING
}
#endif
}
return result;
}
int
_build_initial_pdu_packet(struct session_list *slp, netsnmp_pdu *pdu, int bulk)
{
netsnmp_session *session;
struct snmp_internal_session *isp;
netsnmp_transport *transport = NULL;
u_char *pktbuf = NULL, *packet = NULL;
size_t pktbuf_len = 0, offset = 0, length = 0, orig_length = 0;
int result, orig_count = 0, curr_count = 0;
if (slp == NULL) {
return SNMPERR_GENERR;
}
session = slp->session;
isp = slp->internal;
transport = slp->transport;
if (!session || !isp || !transport) {
DEBUGMSGTL(("sess_async_send", "send fail: closing...\n"));
return SNMPERR_GENERR;
}
if (pdu == NULL) {
session->s_snmp_errno = SNMPERR_NULL_PDU;
return SNMPERR_GENERR;
}
SNMP_FREE(isp->obuf); /* should already be NULL */
session->s_snmp_errno = 0;
session->s_errno = 0;
/*
* Check/setup the version.
*/
if (pdu->version == SNMP_DEFAULT_VERSION) {
if (session->version == SNMP_DEFAULT_VERSION) {
session->s_snmp_errno = SNMPERR_BAD_VERSION;
return SNMPERR_GENERR;
}
pdu->version = session->version;
} else if (session->version == SNMP_DEFAULT_VERSION) {
/*
* It's OK
*/
} else if (pdu->version != session->version) {
/*
* ENHANCE: we should support multi-lingual sessions
*/
session->s_snmp_errno = SNMPERR_BAD_VERSION;
return SNMPERR_GENERR;
}
if (NETSNMP_RUNTIME_PROTOCOL_SKIP(pdu->version)) {
DEBUGMSGTL(("sess_async_send", "version disabled at runtime\n"));
session->s_snmp_errno = SNMPERR_BAD_VERSION;
return SNMPERR_GENERR;
}
/*
* do we expect a response?
*/
switch (pdu->command) {
case SNMP_MSG_RESPONSE:
case SNMP_MSG_TRAP:
case SNMP_MSG_TRAP2:
case SNMP_MSG_REPORT:
case AGENTX_MSG_CLEANUPSET:
case AGENTX_MSG_RESPONSE:
pdu->flags &= ~UCD_MSG_FLAG_EXPECT_RESPONSE;
break;
default:
pdu->flags |= UCD_MSG_FLAG_EXPECT_RESPONSE;
break;
}
/*
* check to see if we need a v3 engineID probe
*/
if ((pdu->version == SNMP_VERSION_3) &&
(pdu->flags & UCD_MSG_FLAG_EXPECT_RESPONSE) &&
(session->securityEngineIDLen == 0) &&
(0 == (session->flags & SNMP_FLAGS_DONT_PROBE))) {
int rc;
DEBUGMSGTL(("snmpv3_build", "delayed probe for engineID\n"));
rc = snmpv3_engineID_probe(slp, session);
if (rc == 0)
return 0; /* s_snmp_errno already set */
}
/*
* determine max packet size
*/
if (pdu->msgMaxSize == 0) {
pdu->msgMaxSize = netsnmp_max_send_msg_size();
if (pdu->msgMaxSize > transport->msgMaxSize)
pdu->msgMaxSize = transport->msgMaxSize;
if (pdu->msgMaxSize > session->sndMsgMaxSize)
pdu->msgMaxSize = session->sndMsgMaxSize;
DEBUGMSGTL(("sess_async_send", "max PDU size: %ld\n",
pdu->msgMaxSize));
}
netsnmp_assert(pdu->msgMaxSize > 0);
/*
* allocate initial packet buffer. Buffer will be grown as needed
* while building the packet.
*/
pktbuf_len = SNMP_MIN_MAX_LEN;
if ((pktbuf = (u_char *)malloc(pktbuf_len)) == NULL) {
DEBUGMSGTL(("sess_async_send",
"couldn't malloc initial packet buffer\n"));
session->s_snmp_errno = SNMPERR_MALLOC;
return SNMPERR_MALLOC;
}
#ifdef TEMPORARILY_DISABLED
/*
* NULL variable are allowed in certain PDU types.
* In particular, SNMPv3 engineID probes are of this form.
* There is an internal PDU flag to indicate that this
* is acceptable, but until the construction of engineID
* probes can be amended to set this flag, we'll simply
* skip this test altogether.
*/
if (pdu->variables == NULL) {
switch (pdu->command) {
#ifndef NETSNMP_NO_WRITE_SUPPORT
case SNMP_MSG_SET:
#endif /* !NETSNMP_NO_WRITE_SUPPORT */
case SNMP_MSG_GET:
case SNMP_MSG_GETNEXT:
case SNMP_MSG_GETBULK:
case SNMP_MSG_RESPONSE:
case SNMP_MSG_TRAP2:
case SNMP_MSG_REPORT:
case SNMP_MSG_INFORM:
session->s_snmp_errno = snmp_errno = SNMPERR_NO_VARS;
return SNMPERR_NO_VARS;
case SNMP_MSG_TRAP:
break;
}
}
#endif
/*
* Build the message to send. If a bulk response is too big, switch to
* forward encoding and set a flag to drop varbinds to make it fit.
*/
do {
packet = pktbuf;
length = offset = 0;
result = netsnmp_build_packet(isp, session, pdu, &pktbuf, &pktbuf_len,
&packet, &length);
if (0 != result)
break;
if (orig_count) { /* 2nd pass, see how many varbinds remain */
curr_count = count_varbinds(pdu->variables);
DEBUGMSGTL(("sess_async_send", " vb count: %d -> %d\n", orig_count,
curr_count));
DEBUGMSGTL(("sess_async_send", " pdu_len: %" NETSNMP_PRIz "d -> %" NETSNMP_PRIz "d (max %ld)\n",
orig_length, length, pdu->msgMaxSize));
}
/** if length is less than max size, we're done (success). */
if (length <= pdu->msgMaxSize)
break;
DEBUGMSGTL(("sess_async_send", "length %" NETSNMP_PRIz "d exceeds maximum %ld\n",
length, pdu->msgMaxSize));
/** packet too big. if this is not a bulk request, we're done (err). */
if (!bulk) {
session->s_snmp_errno = SNMPERR_TOO_LONG;
break;
}
/** rebuild bulk response with truncation and fixed size */
pdu->flags |= UCD_MSG_FLAG_FORWARD_ENCODE | UCD_MSG_FLAG_BULK_TOOBIG;
pktbuf_len = pdu->msgMaxSize;
/** save original number of vabinds & length */
if (0 == orig_count) {
curr_count = orig_count = count_varbinds(pdu->variables);
orig_length = length;
}
} while(1);
DEBUGMSGTL(("sess_async_send",
"final pktbuf_len after building packet %" NETSNMP_PRIz "u\n",
pktbuf_len));
if (curr_count != orig_count)
DEBUGMSGTL(("sess_async_send",
"sending %d of %d varbinds (-%d) from bulk response\n",
curr_count, orig_count, orig_count - curr_count));
if (length > pdu->msgMaxSize) {
DEBUGMSGTL(("sess_async_send",
"length of packet (%" NETSNMP_PRIz "u) exceeded pdu maximum (%lu)\n",
length, pdu->msgMaxSize));
netsnmp_assert(SNMPERR_TOO_LONG == session->s_snmp_errno);
}
if ((SNMPERR_TOO_LONG == session->s_snmp_errno) || (result < 0)) {
DEBUGMSGTL(("sess_async_send", "encoding failure\n"));
SNMP_FREE(pktbuf);
return SNMPERR_GENERR;
}
isp->obuf = pktbuf;
isp->obuf_size = pktbuf_len;
isp->opacket = packet;
isp->opacket_len = length;
return SNMPERR_SUCCESS;
}
/*
* These functions send PDUs using an active session:
* snmp_send - traditional API, no callback
* snmp_async_send - traditional API, with callback
* snmp_sess_send - single session API, no callback
* snmp_sess_async_send - single session API, with callback
*
* Call snmp_build to create a serialized packet (the pdu).
* If necessary, set some of the pdu data from the
* session defaults.
* If there is an expected response for this PDU,
* queue a corresponding request on the list
* of outstanding requests for this session,
* and store the callback vectors in the request.
*
* Send the pdu to the target identified by this session.
* Return on success:
* The request id of the pdu is returned, and the pdu is freed.
* Return on failure:
* Zero (0) is returned.
* The caller must call snmp_free_pdu if 0 is returned.
*/
int
snmp_send(netsnmp_session * session, netsnmp_pdu *pdu)
{
return snmp_async_send(session, pdu, NULL, NULL);
}
int
snmp_sess_send(void *sessp, netsnmp_pdu *pdu)
{
return snmp_sess_async_send(sessp, pdu, NULL, NULL);
}
int
snmp_async_send(netsnmp_session * session,
netsnmp_pdu *pdu, snmp_callback callback, void *cb_data)
{
void *sessp = snmp_sess_pointer(session);
return snmp_sess_async_send(sessp, pdu, callback, cb_data);
}
/**
* Send a PDU asynchronously.
*
* @param[in] slp Session pointer.
* @param[in] pdu PDU to send.
* @param[in] callback Callback function called after processing of the PDU
* finished. This function is called if the PDU has not
* been sent or after a response has been received. Must
* not free @pdu.
* @param[in] cb_data Will be passed as fifth argument to @callback.
*
* @return If successful, returns the request id of @pdu and frees @pdu.
* If not successful, returns zero and expects the caller to free @pdu.
*/
static int
_sess_async_send(void *sessp,
netsnmp_pdu *pdu, snmp_callback callback, void *cb_data)
{
struct session_list *slp = (struct session_list *) sessp;
netsnmp_session *session;
struct snmp_internal_session *isp;
netsnmp_transport *transport = NULL;
int result;
long reqid;
if (slp == NULL || NULL == slp->session || NULL ==slp->internal ||
NULL == slp->transport) {
return 0;
}
session = slp->session;
isp = slp->internal;
transport = slp->transport;
if (NULL == isp->opacket) {
result = _build_initial_pdu_packet(slp, pdu, 0);
if ((SNMPERR_SUCCESS != result) || (NULL == isp->opacket)) {
if (callback) {
switch (session->s_snmp_errno) {
/*
* some of these probably don't make sense here, but
* it's a rough first cut.
*/
case SNMPERR_BAD_ENG_ID:
case SNMPERR_BAD_SEC_LEVEL:
case SNMPERR_UNKNOWN_SEC_MODEL:
case SNMPERR_UNKNOWN_ENG_ID:
case SNMPERR_UNKNOWN_USER_NAME:
case SNMPERR_UNSUPPORTED_SEC_LEVEL:
case SNMPERR_AUTHENTICATION_FAILURE:
case SNMPERR_NOT_IN_TIME_WINDOW:
case SNMPERR_USM_GENERICERROR:
case SNMPERR_USM_UNKNOWNSECURITYNAME:
case SNMPERR_USM_UNSUPPORTEDSECURITYLEVEL:
case SNMPERR_USM_ENCRYPTIONERROR:
case SNMPERR_USM_AUTHENTICATIONFAILURE:
case SNMPERR_USM_PARSEERROR:
case SNMPERR_USM_UNKNOWNENGINEID:
case SNMPERR_USM_NOTINTIMEWINDOW:
callback(NETSNMP_CALLBACK_OP_SEC_ERROR, session,
pdu->reqid, pdu, cb_data);
break;
case SNMPERR_TIMEOUT: /* engineID probe timed out */
callback(NETSNMP_CALLBACK_OP_TIMED_OUT, session,
pdu->reqid, pdu, cb_data);
break;
default:
callback(NETSNMP_CALLBACK_OP_SEND_FAILED, session,
pdu->reqid, pdu, cb_data);
break;
}
}
/** no packet to send?? */
return 0;
}
}
/*
* Send the message.
*/
DEBUGMSGTL(("sess_process_packet", "sending message id#%ld reqid#%ld len %"
NETSNMP_PRIz "u\n", pdu->msgid, pdu->reqid, isp->opacket_len));
result = netsnmp_transport_send(transport, isp->opacket, isp->opacket_len,
&(pdu->transport_data),
&(pdu->transport_data_length));
SNMP_FREE(isp->obuf);
isp->opacket = NULL; /* opacket was in obuf, so no free needed */
isp->opacket_len = 0;
if (result < 0) {
session->s_snmp_errno = SNMPERR_BAD_SENDTO;
session->s_errno = errno;
if (callback)
callback(NETSNMP_CALLBACK_OP_SEND_FAILED, session,
pdu->reqid, pdu, cb_data);
return 0;
}
reqid = pdu->reqid;
/*
* Bug 2387: 0 is a valid request id, so since reqid is used as a return
* code with 0 meaning an error, set reqid to 1 if there is no error. This
* does not affect the request id in the packet and fixes a memory leak
* for incoming PDUs with a request id of 0. This could cause some
* confusion if the caller is expecting the request id to match the
* return code, as the documentation states it will. Most example code
* just checks for non-zero, so hopefully this wont be an issue.
*/
if (0 == reqid && (SNMPERR_SUCCESS == session->s_snmp_errno))
++reqid;
/*
* Add to pending requests list if we expect a response.
*/
if (pdu->flags & UCD_MSG_FLAG_EXPECT_RESPONSE) {
netsnmp_request_list *rp;
struct timeval tv;
rp = (netsnmp_request_list *) calloc(1,
sizeof(netsnmp_request_list));
if (rp == NULL) {
session->s_snmp_errno = SNMPERR_GENERR;
return 0;
}
netsnmp_get_monotonic_clock(&tv);
rp->pdu = pdu;
rp->request_id = pdu->reqid;
rp->message_id = pdu->msgid;
rp->callback = callback;
rp->cb_data = cb_data;
rp->retries = 0;
if (pdu->flags & UCD_MSG_FLAG_PDU_TIMEOUT) {
rp->timeout = pdu->time * 1000000L;
} else {
rp->timeout = session->timeout;
}
rp->timeM = tv;
tv.tv_usec += rp->timeout;
tv.tv_sec += tv.tv_usec / 1000000L;
tv.tv_usec %= 1000000L;
rp->expireM = tv;
/*
* XX lock should be per session !
*/
snmp_res_lock(MT_LIBRARY_ID, MT_LIB_SESSION);
if (isp->requestsEnd) {
rp->next_request = isp->requestsEnd->next_request;
isp->requestsEnd->next_request = rp;
isp->requestsEnd = rp;
} else {
rp->next_request = isp->requests;
isp->requests = rp;
isp->requestsEnd = rp;
}
snmp_res_unlock(MT_LIBRARY_ID, MT_LIB_SESSION);
} else {
/*
* No response expected...
*/
if (reqid) {
/*
* Free v1 or v2 TRAP PDU iff no error
*/
snmp_free_pdu(pdu);
}
}
return reqid;
}
/**
* Send a PDU asynchronously.
*
* @param[in] sessp Session pointer.
* @param[in] pdu PDU to send.
* @param[in] callback Callback function called after processing of the PDU
* finished. This function is called if the PDU has not
* been sent or after a response has been received. Must
* not free @p pdu.
* @param[in] cb_data Will be passed as fifth argument to @p callback.
*
* @return If successful, returns the request id of @p pdu and frees @p pdu.
* If not successful, returns zero and expects the caller to free @p pdu.
*/
int
snmp_sess_async_send(void *sessp,
netsnmp_pdu *pdu,
snmp_callback callback, void *cb_data)
{
int rc;
if (sessp == NULL) {
snmp_errno = SNMPERR_BAD_SESSION; /*MTCRITICAL_RESOURCE */
return (0);
}
/*
* send pdu
*/
rc = _sess_async_send(sessp, pdu, callback, cb_data);
if (rc == 0) {
struct session_list *psl;
netsnmp_session *pss;
psl = (struct session_list *) sessp;
pss = psl->session;
SET_SNMP_ERROR(pss->s_snmp_errno);
}
return rc;
}
/*
* Frees the variable and any malloc'd data associated with it.
*/
void
snmp_free_var_internals(netsnmp_variable_list * var)
{
if (!var)
return;
if (var->name != var->name_loc)
SNMP_FREE(var->name);
if (var->val.string != var->buf)
SNMP_FREE(var->val.string);
if (var->data) {
if (var->dataFreeHook) {
var->dataFreeHook(var->data);
var->data = NULL;
} else {
SNMP_FREE(var->data);
}
}
}
void
snmp_free_var(netsnmp_variable_list * var)
{
snmp_free_var_internals(var);
free((char *) var);
}
void
snmp_free_varbind(netsnmp_variable_list * var)
{
netsnmp_variable_list *ptr;
while (var) {
ptr = var->next_variable;
snmp_free_var(var);
var = ptr;
}
}
/*
* Frees the pdu and any malloc'd data associated with it.
*/
void
snmp_free_pdu(netsnmp_pdu *pdu)
{
struct snmp_secmod_def *sptr;
if (!pdu)
return;
free_securityStateRef(pdu);
if ((sptr = find_sec_mod(pdu->securityModel)) != NULL &&
sptr->pdu_free != NULL) {
(*sptr->pdu_free) (pdu);
}
snmp_free_varbind(pdu->variables);
free(pdu->enterprise);
free(pdu->community);
free(pdu->contextEngineID);
free(pdu->securityEngineID);
free(pdu->contextName);
free(pdu->securityName);
free(pdu->transport_data);
free(pdu);
}
netsnmp_pdu *
snmp_create_sess_pdu(netsnmp_transport *transport, void *opaque,
size_t olength)
{
netsnmp_pdu *pdu = (netsnmp_pdu *)calloc(1, sizeof(netsnmp_pdu));
if (pdu == NULL) {
DEBUGMSGTL(("sess_process_packet", "can't malloc space for PDU\n"));
return NULL;
}
/*
* Save the transport-level data specific to this reception (e.g. UDP
* source address).
*/
pdu->transport_data = opaque;
pdu->transport_data_length = olength;
pdu->tDomain = transport->domain;
pdu->tDomainLen = transport->domain_length;
return pdu;
}
/*
* This function parses a packet into a PDU
*/
static netsnmp_pdu *
_sess_process_packet_parse_pdu(void *sessp, netsnmp_session * sp,
struct snmp_internal_session *isp,
netsnmp_transport *transport,
void *opaque, int olength,
u_char * packetptr, int length)
{
netsnmp_pdu *pdu;
int ret = 0;
int dump = 0, filter = 0;
debug_indent_reset();
DEBUGMSGTL(("sess_process_packet",
"session %p fd %d pkt %p length %d\n", sessp,
transport->sock, packetptr, length));
dump = netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID,
NETSNMP_DS_LIB_DUMP_PACKET);
#ifndef NETSNMP_FEATURE_REMOVE_FILTER_SOURCE
filter = netsnmp_ds_get_int(NETSNMP_DS_LIBRARY_ID,
NETSNMP_DS_LIB_FILTER_TYPE);
#endif
if (dump || filter) {
int filtered = 0;
char *addrtxt = netsnmp_transport_peer_string(transport, opaque, olength);
snmp_log(LOG_DEBUG, "\nReceived %d byte packet from %s\n",
length, addrtxt);
if (dump)
xdump(packetptr, length, "");
#ifndef NETSNMP_FEATURE_REMOVE_FILTER_SOURCE
if (filter) {
char *sourceaddr = NULL, *c = strchr(addrtxt, '[');
const char *dropstr = NULL;
if (c) {
sourceaddr = ++c;
c = strchr(sourceaddr, ']');
if (c)
*c = 0;
filtered = netsnmp_transport_filter_check(sourceaddr);
}
if ((filter == -1) && filtered)
dropstr = "matched blocklist";
else if ((filter == 1) && !filtered)
dropstr = "didn't match acceptlist";
if (dropstr) {
DEBUGMSGTL(("sess_process_packet:filter",
"packet from %s %s\n",
sourceaddr ? sourceaddr : "UNKNOWN", dropstr));
SNMP_FREE(opaque);
SNMP_FREE(addrtxt);
return NULL;
}
}
#endif
SNMP_FREE(addrtxt);
}
/*
* Do transport-level filtering (e.g. IP-address based allow/deny).
*/
if (isp->hook_pre) {
if (isp->hook_pre(sp, transport, opaque, olength) == 0) {
DEBUGMSGTL(("sess_process_packet", "pre-parse fail\n"));
SNMP_FREE(opaque);
return NULL;
}
}
if (isp->hook_create_pdu) {
pdu = isp->hook_create_pdu(transport, opaque, olength);
} else {
pdu = snmp_create_sess_pdu(transport, opaque, olength);
}
if (pdu == NULL) {
snmp_log(LOG_ERR, "pdu failed to be created\n");
SNMP_FREE(opaque);
return NULL;
}
/* if the transport was a magic tunnel, mark the PDU as having come
through one. */
if (transport->flags & NETSNMP_TRANSPORT_FLAG_TUNNELED) {
pdu->flags |= UCD_MSG_FLAG_TUNNELED;
}
if (isp->hook_parse) {
ret = isp->hook_parse(sp, pdu, packetptr, length);
} else {
ret = snmp_parse(sessp, sp, pdu, packetptr, length);
}
DEBUGMSGTL(("sess_process_packet", "received message id#%ld reqid#%ld len "
"%u\n", pdu->msgid, pdu->reqid, length));
if (ret != SNMP_ERR_NOERROR) {
DEBUGMSGTL(("sess_process_packet", "parse fail\n"));
}
if (isp->hook_post) {
if (isp->hook_post(sp, pdu, ret) == 0) {
DEBUGMSGTL(("sess_process_packet", "post-parse fail\n"));
ret = SNMPERR_ASN_PARSE_ERR;
}
}
if (ret != SNMP_ERR_NOERROR) {
snmp_free_pdu(pdu);
return NULL;
}
return pdu;
}
/* Remove request @rp from session @isp. @orp is the request before @rp. */
static void
remove_request(struct snmp_internal_session *isp,
netsnmp_request_list *orp, netsnmp_request_list *rp)
{
if (orp)
orp->next_request = rp->next_request;
else
isp->requests = rp->next_request;
if (isp->requestsEnd == rp)
isp->requestsEnd = orp;
snmp_free_pdu(rp->pdu);
}
/*
* This function processes a PDU and calls the relevant callbacks.
*/
static int
_sess_process_packet_handle_pdu(void *sessp, netsnmp_session * sp,
struct snmp_internal_session *isp,
netsnmp_transport *transport, netsnmp_pdu *pdu)
{
struct session_list *slp = (struct session_list *) sessp;
netsnmp_request_list *rp, *orp = NULL;
int handled = 0;
if (pdu->flags & UCD_MSG_FLAG_RESPONSE_PDU) {
/*
* Call USM to free any securityStateRef supplied with the message.
*/
free_securityStateRef(pdu);
for (rp = isp->requests; rp; orp = rp, rp = rp->next_request) {
snmp_callback callback;
void *magic;
if (pdu->version == SNMP_VERSION_3) {
/*
* msgId must match for v3 messages.
*/
if (rp->message_id != pdu->msgid) {
DEBUGMSGTL(("sess_process_packet", "unmatched msg id: %ld != %ld\n",
rp->message_id, pdu->msgid));
continue;
}
/*
* Check that message fields match original, if not, no further
* processing.
*/
if (!snmpv3_verify_msg(rp, pdu)) {
break;
}
} else {
if (rp->request_id != pdu->reqid) {
continue;
}
}
if (rp->callback) {
callback = rp->callback;
magic = rp->cb_data;
} else {
callback = sp->callback;
magic = sp->callback_magic;
}
handled = 1;
/*
* MTR snmp_res_lock(MT_LIBRARY_ID, MT_LIB_SESSION); ?* XX lock
* should be per session !
*/
if (callback == NULL
|| callback(NETSNMP_CALLBACK_OP_RECEIVED_MESSAGE, sp,
pdu->reqid, pdu, magic) == 1) {
if (pdu->command == SNMP_MSG_REPORT) {
if (sp->s_snmp_errno == SNMPERR_NOT_IN_TIME_WINDOW ||
snmpv3_get_report_type(pdu) ==
SNMPERR_NOT_IN_TIME_WINDOW) {
/*
* trigger immediate retry on recoverable Reports
* * (notInTimeWindow), incr_retries == TRUE to prevent
* * inifinite resend
*/
if (rp->retries <= sp->retries) {
snmp_resend_request(slp, orp, rp, TRUE);
break;
} else {
/* We're done with retries, so no longer waiting for a response */
if (callback) {
callback(NETSNMP_CALLBACK_OP_SEC_ERROR, sp,
pdu->reqid, pdu, magic);
}
}
} else {
if (SNMPV3_IGNORE_UNAUTH_REPORTS) {
break;
} else { /* We're done with retries */
if (callback) {
callback(NETSNMP_CALLBACK_OP_SEC_ERROR, sp,
pdu->reqid, pdu, magic);
}
}
}
/*
* Handle engineID discovery.
*/
if (!sp->securityEngineIDLen && pdu->securityEngineIDLen) {
sp->securityEngineID =
(u_char *) malloc(pdu->securityEngineIDLen);
if (sp->securityEngineID == NULL) {
/*
* TODO FIX: recover after message callback *?
*/
snmp_log(LOG_ERR, "malloc failed handling pdu\n");
snmp_free_pdu(pdu);
return -1;
}
memcpy(sp->securityEngineID, pdu->securityEngineID,
pdu->securityEngineIDLen);
sp->securityEngineIDLen = pdu->securityEngineIDLen;
if (!sp->contextEngineIDLen) {
sp->contextEngineID =
(u_char *) malloc(pdu->
securityEngineIDLen);
if (sp->contextEngineID == NULL) {
/*
* TODO FIX: recover after message callback *?
*/
snmp_log(LOG_ERR, "malloc failed handling pdu\n");
snmp_free_pdu(pdu);
return -1;
}
memcpy(sp->contextEngineID,
pdu->securityEngineID,
pdu->securityEngineIDLen);
sp->contextEngineIDLen =
pdu->securityEngineIDLen;
}
}
}
/*
* Successful, so delete request.
*/
remove_request(isp, orp, rp);
free(rp);
/*
* There shouldn't be any more requests with the same reqid.
*/
break;
}
/*
* MTR snmp_res_unlock(MT_LIBRARY_ID, MT_LIB_SESSION); ?* XX lock should be per session !
*/
}
} else {
if (sp->callback) {
/*
* MTR snmp_res_lock(MT_LIBRARY_ID, MT_LIB_SESSION);
*/
handled = 1;
sp->callback(NETSNMP_CALLBACK_OP_RECEIVED_MESSAGE,
sp, pdu->reqid, pdu, sp->callback_magic);
/*
* MTR snmp_res_unlock(MT_LIBRARY_ID, MT_LIB_SESSION);
*/
}
}
if (!handled) {
if (sp->flags & SNMP_FLAGS_SHARED_SOCKET)
return -2;
snmp_increment_statistic(STAT_SNMPUNKNOWNPDUHANDLERS);
DEBUGMSGTL(("sess_process_packet", "unhandled PDU\n"));
}
snmp_free_pdu(pdu);
return 0;
}
/*
* This function processes a complete (according to asn_check_packet or the
* AgentX equivalent) packet, parsing it into a PDU and calling the relevant
* callbacks. On entry, packetptr points at the packet in the session's
* buffer and length is the length of the packet. Return codes:
* 0: pdu handled (pdu deleted)
* -1: parse error (pdu deleted)
* -2: pdu not found for shared session (pdu NOT deleted)
*/
static int
_sess_process_packet(void *sessp, netsnmp_session * sp,
struct snmp_internal_session *isp,
netsnmp_transport *transport,
void *opaque, int olength,
u_char * packetptr, int length)
{
struct session_list *slp = (struct session_list *) sessp;
netsnmp_pdu *pdu;
int rc;
pdu = _sess_process_packet_parse_pdu(sessp, sp, isp, transport, opaque,
olength, packetptr, length);
if (NULL == pdu)
return -1;
/*
* find session to process pdu. usually that will be the current session,
* but with the introduction of shared transports, another session may
* have the same socket.
*/
do {
rc = _sess_process_packet_handle_pdu(sessp, sp, isp, transport, pdu);
if (-2 != rc || !(transport->flags & NETSNMP_TRANSPORT_FLAG_SHARED))
break;
/** -2 means pdu not in request list. check other sessions */
do {
slp = slp->next;
} while (slp && slp->transport->sock != transport->sock);
if (!slp)
break; /* no more sessions with same socket */
sp = slp->session;
isp = slp->internal;
transport = slp->transport;
} while(slp);
if (-2 == rc) { /* did not find session for pdu */
snmp_increment_statistic(STAT_SNMPUNKNOWNPDUHANDLERS);
DEBUGMSGTL(("sess_process_packet", "unhandled PDU\n"));
snmp_free_pdu(pdu);
}
return rc;
}
/*
* Checks to see if any of the fd's set in the fdset belong to
* snmp. Each socket with it's fd set has a packet read from it
* and snmp_parse is called on the packet received. The resulting pdu
* is passed to the callback routine for that session. If the callback
* routine returns successfully, the pdu and it's request are deleted.
*/
void
snmp_read(fd_set * fdset)
{
netsnmp_large_fd_set lfdset;
netsnmp_large_fd_set_init(&lfdset, FD_SETSIZE);
netsnmp_copy_fd_set_to_large_fd_set(&lfdset, fdset);
snmp_read2(&lfdset);
netsnmp_large_fd_set_cleanup(&lfdset);
}
void
snmp_read2(netsnmp_large_fd_set * fdset)
{
struct session_list *slp;
snmp_res_lock(MT_LIBRARY_ID, MT_LIB_SESSION);
for (slp = Sessions; slp; slp = slp->next) {
snmp_sess_read2((void *) slp, fdset);
}
snmp_res_unlock(MT_LIBRARY_ID, MT_LIB_SESSION);
}
/*
* accept new connections
* returns 0 if success, -1 if fail
*/
static int
_sess_read_accept(void *sessp)
{
struct session_list *slp = (struct session_list *) sessp;
netsnmp_session *sp = slp ? slp->session : NULL;
struct snmp_internal_session *isp = slp ? slp->internal : NULL;
netsnmp_transport *transport = slp ? slp->transport : NULL;
netsnmp_transport *new_transport;
struct session_list *nslp;
int data_sock;
if (NULL == sessp || NULL == sp || NULL == transport || NULL == isp ||
!(transport->flags & NETSNMP_TRANSPORT_FLAG_LISTEN))
return -1;
data_sock = transport->f_accept(transport);
if (data_sock < 0) {
sp->s_snmp_errno = SNMPERR_BAD_RECVFROM;
sp->s_errno = errno;
snmp_set_detail(strerror(errno));
return -1;
}
/*
* We've successfully accepted a new stream-based connection.
* It's not too clear what should happen here if we are using the
* single-session API at this point. Basically a "session
* accepted" callback is probably needed to hand the new session
* over to the application.
*
* However, for now, as in th original snmp_api, we will ASSUME
* that we're using the traditional API, and simply add the new
* session to the list. Note we don't have to get the Session
* list lock here, because under that assumption we already hold
* it (this is also why we don't just use snmp_add).
*
* The moral of the story is: don't use listening stream-based
* transports in a multi-threaded environment because something
* will go HORRIBLY wrong (and also that SNMP/TCP is not trivial).
*
* Another open issue: what should happen to sockets that have
* been accept()ed from a listening socket when that original
* socket is closed? If they are left open, then attempting to
* re-open the listening socket will fail, which is semantically
* confusing. Perhaps there should be some kind of chaining in
* the transport structure so that they can all be closed.
* Discuss. ;-)
*/
new_transport=netsnmp_transport_copy(transport);
if (new_transport == NULL) {
sp->s_snmp_errno = SNMPERR_MALLOC;
sp->s_errno = errno;
snmp_set_detail(strerror(errno));
return -1;
}
nslp = NULL;
new_transport->sock = data_sock;
new_transport->flags &= ~NETSNMP_TRANSPORT_FLAG_LISTEN;
nslp = (struct session_list *)
snmp_sess_add_ex(sp, new_transport, isp->hook_pre, isp->hook_parse,
isp->hook_post, isp->hook_build,
isp->hook_realloc_build, isp->check_packet,
isp->hook_create_pdu);
if (nslp != NULL) {
snmp_session_insert(nslp);
/** Tell the new session about its existance if possible. */
DEBUGMSGTL(("sess_read",
"perform callback with op=CONNECT\n"));
(void)nslp->session->callback(NETSNMP_CALLBACK_OP_CONNECT,
nslp->session, 0, NULL,
sp->callback_magic);
}
return 0;
}
/*
* Same as snmp_read, but works just one non-stream session.
* returns 0 if success, -1 if protocol err, -2 if no packet to process
* MTR: can't lock here and at snmp_read
* Beware recursive send maybe inside snmp_read callback function.
*/
static int
_sess_read_dgram_packet(void *sessp, netsnmp_large_fd_set * fdset,
snmp_rcv_packet *rcvp)
{
struct session_list *slp = (struct session_list *) sessp;
netsnmp_session *sp = slp ? slp->session : NULL;
struct snmp_internal_session *isp = slp ? slp->internal : NULL;
netsnmp_transport *transport = slp ? slp->transport : NULL;
if (!sp || !isp || !transport || !rcvp ) {
DEBUGMSGTL(("sess_read_packet", "missing arguments\n"));
return -2;
}
if (transport->flags & NETSNMP_TRANSPORT_FLAG_STREAM)
return -2;
if (NULL != rcvp->packet) {
snmp_log(LOG_WARNING, "overwriting existing saved packet; sess %p\n",
sp);
SNMP_FREE(rcvp->packet);
}
if ((rcvp->packet = (u_char *) malloc(SNMP_MAX_RCV_MSG_SIZE)) == NULL) {
DEBUGMSGTL(("sess_read_packet", "can't malloc %u bytes for packet\n",
SNMP_MAX_RCV_MSG_SIZE));
return -2;
}
rcvp->packet_len = netsnmp_transport_recv(transport, rcvp->packet,
SNMP_MAX_RCV_MSG_SIZE,
&rcvp->opaque, &rcvp->olength);
if (rcvp->packet_len == -1) {
sp->s_snmp_errno = SNMPERR_BAD_RECVFROM;
sp->s_errno = errno;
snmp_set_detail(strerror(errno));
SNMP_FREE(rcvp->packet);
SNMP_FREE(rcvp->opaque);
return -1;
}
/** clear so any other sess sharing this socket won't try reading again */
NETSNMP_LARGE_FD_CLR(transport->sock, fdset);
if (0 == rcvp->packet_len &&
transport->flags & NETSNMP_TRANSPORT_FLAG_EMPTY_PKT) {
/* this allows for a transport that needs to return from
* packet processing that doesn't necessarily have any
* consumable data in it. */
/* reset the flag since it's a per-message flag */
transport->flags &= (~NETSNMP_TRANSPORT_FLAG_EMPTY_PKT);
/** free packet */
SNMP_FREE(rcvp->packet);
SNMP_FREE(rcvp->opaque);
return -2;
}
return 0;
}
/*
* Same as snmp_read, but works just one session.
* returns 0 if success, -1 if fail
* MTR: can't lock here and at snmp_read
* Beware recursive send maybe inside snmp_read callback function.
*/
int
_sess_read(void *sessp, netsnmp_large_fd_set * fdset)
{
struct session_list *slp = (struct session_list *) sessp;
netsnmp_session *sp = slp ? slp->session : NULL;
struct snmp_internal_session *isp = slp ? slp->internal : NULL;
netsnmp_transport *transport = slp ? slp->transport : NULL;
size_t pdulen = 0, rxbuf_len = SNMP_MAX_RCV_MSG_SIZE;
u_char *rxbuf = NULL;
int length = 0, olength = 0, rc = 0;
void *opaque = NULL;
if (NULL == slp || NULL == sp || NULL == isp || NULL == transport) {
snmp_log(LOG_ERR, "bad parameters to _sess_read\n");
return SNMPERR_GENERR;
}
/* to avoid subagent crash */
if (transport->sock < 0) {
snmp_log (LOG_INFO, "transport->sock got negative fd value %d\n",
transport->sock);
return 0;
}
if (!fdset || !(NETSNMP_LARGE_FD_ISSET(transport->sock, fdset))) {
DEBUGMSGTL(("sess_read", "not reading %d (fdset %p set %d)\n",
transport->sock, fdset,
fdset ? NETSNMP_LARGE_FD_ISSET(transport->sock, fdset)
: -9));
return 0;
}
sp->s_snmp_errno = 0;
sp->s_errno = 0;
if (transport->flags & NETSNMP_TRANSPORT_FLAG_LISTEN)
return _sess_read_accept(sessp);
if (!(transport->flags & NETSNMP_TRANSPORT_FLAG_STREAM)) {
snmp_rcv_packet rcvp;
memset(&rcvp, 0x0, sizeof(rcvp));
/** read the packet */
rc = _sess_read_dgram_packet(sessp, fdset, &rcvp);
if (-1 == rc) /* protocol error */
return -1;
else if (-2 == rc) /* no packet to process */
return 0;
rc = _sess_process_packet(sessp, sp, isp, transport,
rcvp.opaque, rcvp.olength,
rcvp.packet, rcvp.packet_len);
SNMP_FREE(rcvp.packet);
/** opaque is freed in _sess_process_packet */
return rc;
}
/** stream transport */
if (isp->packet == NULL) {
/*
* We have no saved packet. Allocate one.
*/
if ((isp->packet = (u_char *) malloc(rxbuf_len)) == NULL) {
DEBUGMSGTL(("sess_read", "can't malloc %" NETSNMP_PRIz
"u bytes for rxbuf\n", rxbuf_len));
return 0;
} else {
rxbuf = isp->packet;
isp->packet_size = rxbuf_len;
isp->packet_len = 0;
}
} else {
/*
* We have saved a partial packet from last time. Extend that, if
* necessary, and receive new data after the old data.
*/
u_char *newbuf;
if (isp->packet_size < isp->packet_len + rxbuf_len) {
newbuf =
(u_char *) realloc(isp->packet,
isp->packet_len + rxbuf_len);
if (newbuf == NULL) {
DEBUGMSGTL(("sess_read",
"can't malloc %" NETSNMP_PRIz
"u more for rxbuf (%" NETSNMP_PRIz "u tot)\n",
rxbuf_len, isp->packet_len + rxbuf_len));
return 0;
} else {
isp->packet = newbuf;
isp->packet_size = isp->packet_len + rxbuf_len;
rxbuf = isp->packet + isp->packet_len;
}
} else {
rxbuf = isp->packet + isp->packet_len;
rxbuf_len = isp->packet_size - isp->packet_len;
}
}
length = netsnmp_transport_recv(transport, rxbuf, rxbuf_len, &opaque,
&olength);
if (0 == length && transport->flags & NETSNMP_TRANSPORT_FLAG_EMPTY_PKT) {
/* this allows for a transport that needs to return from
* packet processing that doesn't necessarily have any
* consumable data in it. */
/* reset the flag since it's a per-message flag */
transport->flags &= (~NETSNMP_TRANSPORT_FLAG_EMPTY_PKT);
return 0;
}
/*
* Remote end closed connection.
*/
if (length <= 0) {
/*
* Alert the application if possible.
*/
if (sp->callback != NULL) {
DEBUGMSGTL(("sess_read", "perform callback with op=DISCONNECT\n"));
(void) sp->callback(NETSNMP_CALLBACK_OP_DISCONNECT, sp, 0,
NULL, sp->callback_magic);
}
/*
* Close socket and mark session for deletion.
*/
DEBUGMSGTL(("sess_read", "fd %d closed\n", transport->sock));
transport->f_close(transport);
SNMP_FREE(isp->packet);
SNMP_FREE(opaque);
return -1;
}
{
u_char *pptr = isp->packet;
void *ocopy = NULL;
isp->packet_len += length;
while (isp->packet_len > 0) {
/*
* Get the total data length we're expecting (and need to wait
* for).
*/
if (isp->check_packet) {
pdulen = isp->check_packet(pptr, isp->packet_len);
} else {
pdulen = asn_check_packet(pptr, isp->packet_len);
}
DEBUGMSGTL(("sess_read",
" loop packet_len %" NETSNMP_PRIz "u, PDU length %"
NETSNMP_PRIz "u\n", isp->packet_len, pdulen));
if (pdulen > SNMP_MAX_PACKET_LEN) {
/*
* Illegal length, drop the connection.
*/
snmp_log(LOG_ERR,
"Received broken packet. Closing session.\n");
if (sp->callback != NULL) {
DEBUGMSGTL(("sess_read",
"perform callback with op=DISCONNECT\n"));
(void)sp->callback(NETSNMP_CALLBACK_OP_DISCONNECT,
sp, 0, NULL, sp->callback_magic);
}
DEBUGMSGTL(("sess_read", "fd %d closed\n", transport->sock));
transport->f_close(transport);
SNMP_FREE(opaque);
/** XXX-rks: why no SNMP_FREE(isp->packet); ?? */
return -1;
}
if (pdulen > isp->packet_len || pdulen == 0) {
/*
* We don't have a complete packet yet. If we've already
* processed a packet, break out so we'll shift this packet
* to the start of the buffer. If we're already at the
* start, simply return and wait for more data to arrive.
*/
DEBUGMSGTL(("sess_read",
"pkt not complete (need %" NETSNMP_PRIz "u got %"
NETSNMP_PRIz "u so far)\n", pdulen,
isp->packet_len));
if (pptr != isp->packet)
break; /* opaque freed for us outside of loop. */
SNMP_FREE(opaque);
return 0;
}
/* We have *at least* one complete packet in the buffer now. If
we have possibly more than one packet, we must copy the opaque
pointer because we may need to reuse it for a later packet. */
if (pdulen < isp->packet_len) {
if (olength > 0 && opaque != NULL) {
ocopy = malloc(olength);
if (ocopy != NULL) {
memcpy(ocopy, opaque, olength);
}
}
} else if (pdulen == isp->packet_len) {
/* Common case -- exactly one packet. No need to copy the
opaque pointer. */
ocopy = opaque;
opaque = NULL;
}
if ((rc = _sess_process_packet(sessp, sp, isp, transport,
ocopy, ocopy?olength:0, pptr,
pdulen))) {
/*
* Something went wrong while processing this packet -- set the
* errno.
*/
if (sp->s_snmp_errno != 0) {
SET_SNMP_ERROR(sp->s_snmp_errno);
}
}
/* ocopy has been free()d by _sess_process_packet by this point,
so set it to NULL. */
ocopy = NULL;
/* Step past the packet we've just dealt with. */
pptr += pdulen;
isp->packet_len -= pdulen;
}
/* If we had more than one packet, then we were working with copies
of the opaque pointer, so we still need to free() the opaque
pointer itself. */
SNMP_FREE(opaque);
if (isp->packet_len >= SNMP_MAX_PACKET_LEN) {
/*
* Obviously this should never happen!
*/
snmp_log(LOG_ERR,
"too large packet_len = %" NETSNMP_PRIz
"u, dropping connection %d\n",
isp->packet_len, transport->sock);
transport->f_close(transport);
/** XXX-rks: why no SNMP_FREE(isp->packet); ?? */
return -1;
} else if (isp->packet_len == 0) {
/*
* This is good: it means the packet buffer contained an integral
* number of PDUs, so we don't have to save any data for next
* time. We can free() the buffer now to keep the memory
* footprint down.
*/
SNMP_FREE(isp->packet);
isp->packet_size = 0;
isp->packet_len = 0;
return rc;
}
/*
* If we get here, then there is a partial packet of length
* isp->packet_len bytes starting at pptr left over. Move that to the
* start of the buffer, and then realloc() the buffer down to size to
* reduce the memory footprint.
*/
memmove(isp->packet, pptr, isp->packet_len);
DEBUGMSGTL(("sess_read",
"end: memmove(%p, %p, %" NETSNMP_PRIz "u); realloc(%p, %"
NETSNMP_PRIz "u)\n",
isp->packet, pptr, isp->packet_len,
isp->packet, isp->packet_len));
if ((rxbuf = (u_char *)realloc(isp->packet, isp->packet_len)) == NULL) {
/*
* I don't see why this should ever fail, but it's not a big deal.
*/
DEBUGMSGTL(("sess_read", "realloc() failed\n"));
} else {
DEBUGMSGTL(("sess_read", "realloc() okay, old buffer %p, new %p\n",
isp->packet, rxbuf));
isp->packet = rxbuf;
isp->packet_size = isp->packet_len;
}
}
return rc;
}
/*
* returns 0 if success, -1 if fail
*/
int
snmp_sess_read(void *sessp, fd_set * fdset)
{
int rc;
netsnmp_large_fd_set lfdset;
netsnmp_large_fd_set_init(&lfdset, FD_SETSIZE);
netsnmp_copy_fd_set_to_large_fd_set(&lfdset, fdset);
rc = snmp_sess_read2(sessp, &lfdset);
netsnmp_large_fd_set_cleanup(&lfdset);
return rc;
}
int
snmp_sess_read2(void *sessp, netsnmp_large_fd_set * fdset)
{
struct session_list *psl;
netsnmp_session *pss;
int rc;
rc = _sess_read(sessp, fdset);
psl = (struct session_list *) sessp;
pss = psl->session;
if (rc && pss->s_snmp_errno) {
SET_SNMP_ERROR(pss->s_snmp_errno);
}
return rc;
}
/**
* Returns info about what snmp requires from a select statement.
* numfds is the number of fds in the list that are significant.
* All file descriptors opened for SNMP are OR'd into the fdset.
* If activity occurs on any of these file descriptors, snmp_read
* should be called with that file descriptor set
*
* The timeout is the latest time that SNMP can wait for a timeout. The
* select should be done with the minimum time between timeout and any other
* timeouts necessary. This should be checked upon each invocation of select.
* If a timeout is received, snmp_timeout should be called to check if the
* timeout was for SNMP. (snmp_timeout is idempotent)
*
* The value of block indicates how the timeout value is interpreted.
* If block is true on input, the timeout value will be treated as undefined,
* but it must be available for setting in snmp_select_info. On return,
* block is set to true if the value returned for timeout is undefined;
* when block is set to false, timeout may be used as a parmeter to 'select'.
*
* snmp_select_info returns the number of open sockets. (i.e. The number of
* sessions open)
*
* @see See also snmp_sess_select_info2_flags().
*/
int
snmp_select_info(int *numfds, fd_set *fdset, struct timeval *timeout,
int *block)
{
return snmp_sess_select_info(NULL, numfds, fdset, timeout, block);
}
/**
* @see See also snmp_sess_select_info2_flags().
*/
int
snmp_select_info2(int *numfds, netsnmp_large_fd_set *fdset,
struct timeval *timeout, int *block)
{
return snmp_sess_select_info2(NULL, numfds, fdset, timeout, block);
}
/**
* @see See also snmp_sess_select_info2_flags().
*/
int
snmp_sess_select_info(void *sessp, int *numfds, fd_set *fdset,
struct timeval *timeout, int *block)
{
return snmp_sess_select_info_flags(sessp, numfds, fdset, timeout, block,
NETSNMP_SELECT_NOFLAGS);
}
/**
* @see See also snmp_sess_select_info2_flags().
*/
int
snmp_sess_select_info_flags(void *sessp, int *numfds, fd_set *fdset,
struct timeval *timeout, int *block, int flags)
{
int rc;
netsnmp_large_fd_set lfdset;
netsnmp_large_fd_set_init(&lfdset, FD_SETSIZE);
netsnmp_copy_fd_set_to_large_fd_set(&lfdset, fdset);
rc = snmp_sess_select_info2_flags(sessp, numfds, &lfdset, timeout,
block, flags);
if (netsnmp_copy_large_fd_set_to_fd_set(fdset, &lfdset) < 0) {
snmp_log(LOG_ERR,
"Use snmp_sess_select_info2() for processing"
" large file descriptors\n");
}
netsnmp_large_fd_set_cleanup(&lfdset);
return rc;
}
/**
* @see See also snmp_sess_select_info2_flags().
*/
int
snmp_sess_select_info2(void *sessp, int *numfds, netsnmp_large_fd_set *fdset,
struct timeval *timeout, int *block)
{
return snmp_sess_select_info2_flags(sessp, numfds, fdset, timeout, block,
NETSNMP_SELECT_NOFLAGS);
}
/**
* Compute/update the arguments to be passed to select().
*
* @param[in] sessp Which sessions to process: either a pointer to a
* specific session or NULL which means to process all sessions.
* @param[in,out] numfds On POSIX systems one more than the the largest file
* descriptor that is present in *fdset. On systems that use Winsock (MinGW
* and MSVC), do not use the value written into *numfds.
* @param[in,out] fdset A large file descriptor set to which all file
* descriptors will be added that are associated with one of the examined
* sessions.
* @param[in,out] timeout On input, if *block = 1, the maximum time the caller
* will block while waiting for Net-SNMP activity. On output, if this function
* has set *block to 0, the maximum time the caller is allowed to wait before
* invoking the Net-SNMP processing functions (snmp_read(), snmp_timeout()
* and run_alarms()). If this function has set *block to 1, *timeout won't
* have been modified and no alarms are active.
* @param[in,out] block On input, whether the caller prefers to block forever
* when no alarms are active. On output, 0 means that no alarms are active
* nor that there is a timeout pending for any of the processed sessions.
* @param[in] flags Either 0 or NETSNMP_SELECT_NOALARMS.
*
* @return Number of sessions processed by this function.
*
* @see See also agent_check_and_process() for an example of how to use this
* function.
*/
int
snmp_sess_select_info2_flags(void *sessp, int *numfds,
netsnmp_large_fd_set * fdset,
struct timeval *timeout, int *block, int flags)
{
struct session_list *slp, *next = NULL;
netsnmp_request_list *rp;
struct timeval now, earliest, alarm_tm;
int active = 0, requests = 0;
int next_alarm = 0;
timerclear(&earliest);
/*
* For each session examined, add its socket to the fdset,
* and if it is the earliest timeout to expire, mark it as lowest.
* If a single session is specified, do just for that session.
*/
DEBUGMSGTL(("sess_select", "for %s session%s: ",
sessp ? "single" : "all", sessp ? "" : "s"));
for (slp = sessp ? sessp : Sessions; slp; slp = next) {
next = slp->next;
if (slp->transport == NULL) {
/*
* Close in progress -- skip this one.
*/
DEBUGMSG(("sess_select", "skip "));
continue;
}
if (slp->transport->sock == -1) {
/*
* This session was marked for deletion.
*/
DEBUGMSG(("sess_select", "delete\n"));
if (sessp == NULL) {
snmp_close(slp->session);
} else {
snmp_sess_close(slp);
}
DEBUGMSGTL(("sess_select", "for %s session%s: ",
sessp ? "single" : "all", sessp ? "" : "s"));
continue;
}
DEBUGMSG(("sess_select", "%d ", slp->transport->sock));
if ((slp->transport->sock + 1) > *numfds) {
*numfds = (slp->transport->sock + 1);
}
NETSNMP_LARGE_FD_SET(slp->transport->sock, fdset);
if (slp->internal != NULL && slp->internal->requests) {
/*
* Found another session with outstanding requests.
*/
requests++;
for (rp = slp->internal->requests; rp; rp = rp->next_request) {
if (!timerisset(&earliest)
|| (timerisset(&rp->expireM)
&& timercmp(&rp->expireM, &earliest, <))) {
earliest = rp->expireM;
DEBUGMSG(("verbose:sess_select","(to in %d.%06d sec) ",
(int)earliest.tv_sec, (int)earliest.tv_usec));
}
}
}
active++;
if (sessp) {
/*
* Single session processing.
*/
break;
}
}
DEBUGMSG(("sess_select", "\n"));
netsnmp_get_monotonic_clock(&now);
if (netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID,
NETSNMP_DS_LIB_ALARM_DONT_USE_SIG) &&
!(flags & NETSNMP_SELECT_NOALARMS)) {
next_alarm = netsnmp_get_next_alarm_time(&alarm_tm, &now);
if (next_alarm)
DEBUGMSGT(("sess_select","next alarm at %ld.%06ld sec\n",
(long)alarm_tm.tv_sec, (long)alarm_tm.tv_usec));
}
if (next_alarm == 0 && requests == 0) {
/*
* If none are active, skip arithmetic.
*/
DEBUGMSGT(("sess_select","blocking:no session requests or alarms.\n"));
*block = 1; /* can block - timeout value is undefined if no requests */
return active;
}
if (next_alarm &&
(!timerisset(&earliest) || timercmp(&alarm_tm, &earliest, <)))
earliest = alarm_tm;
NETSNMP_TIMERSUB(&earliest, &now, &earliest);
if (earliest.tv_sec < 0) {
time_t overdue_ms = -(earliest.tv_sec * 1000 + earliest.tv_usec / 1000);
if (overdue_ms >= 10)
DEBUGMSGT(("verbose:sess_select","timer overdue by %ld ms\n",
(long) overdue_ms));
timerclear(&earliest);
} else {
DEBUGMSGT(("verbose:sess_select","timer due in %d.%06d sec\n",
(int)earliest.tv_sec, (int)earliest.tv_usec));
}
/*
* if it was blocking before or our delta time is less, reset timeout
*/
if ((*block || (timercmp(&earliest, timeout, <)))) {
DEBUGMSGT(("verbose:sess_select",
"setting timer to %d.%06d sec, clear block (was %d)\n",
(int)earliest.tv_sec, (int)earliest.tv_usec, *block));
*timeout = earliest;
*block = 0;
}
return active;
}
/*
* snmp_timeout should be called whenever the timeout from snmp_select_info
* expires, but it is idempotent, so snmp_timeout can be polled (probably a
* cpu expensive proposition). snmp_timeout checks to see if any of the
* sessions have an outstanding request that has timed out. If it finds one
* (or more), and that pdu has more retries available, a new packet is formed
* from the pdu and is resent. If there are no more retries available, the
* callback for the session is used to alert the user of the timeout.
*/
void
snmp_timeout(void)
{
struct session_list *slp;
snmp_res_lock(MT_LIBRARY_ID, MT_LIB_SESSION);
for (slp = Sessions; slp; slp = slp->next) {
snmp_sess_timeout((void *) slp);
}
snmp_res_unlock(MT_LIBRARY_ID, MT_LIB_SESSION);
}
static int
snmp_resend_request(struct session_list *slp, netsnmp_request_list *orp,
netsnmp_request_list *rp, int incr_retries)
{
struct snmp_internal_session *isp;
netsnmp_session *sp;
netsnmp_transport *transport;
u_char *pktbuf = NULL, *packet = NULL;
size_t pktbuf_len = 0, length = 0;
struct timeval tv, now;
int result = 0;
sp = slp->session;
isp = slp->internal;
transport = slp->transport;
if (!sp || !isp || !transport) {
DEBUGMSGTL(("sess_read", "resend fail: closing...\n"));
return 0;
}
if ((pktbuf = (u_char *)malloc(2048)) == NULL) {
DEBUGMSGTL(("sess_resend",
"couldn't malloc initial packet buffer\n"));
return 0;
} else {
pktbuf_len = 2048;
}
if (incr_retries) {
rp->retries++;
}
/*
* Always increment msgId for resent messages.
*/
rp->pdu->msgid = rp->message_id = snmp_get_next_msgid();
result = netsnmp_build_packet(isp, sp, rp->pdu, &pktbuf, &pktbuf_len,
&packet, &length);
if (result < 0) {
/*
* This should never happen.
*/
DEBUGMSGTL(("sess_resend", "encoding failure\n"));
SNMP_FREE(pktbuf);
return -1;
}
DEBUGMSGTL(("sess_process_packet", "resending message id#%ld reqid#%ld "
"rp_reqid#%ld rp_msgid#%ld len %" NETSNMP_PRIz "u\n",
rp->pdu->msgid, rp->pdu->reqid, rp->request_id, rp->message_id, length));
result = netsnmp_transport_send(transport, packet, length,
&(rp->pdu->transport_data),
&(rp->pdu->transport_data_length));
/*
* We are finished with the local packet buffer, if we allocated one (due
* to there being no saved packet).
*/
if (pktbuf != NULL) {
SNMP_FREE(pktbuf);
packet = NULL;
}
if (result < 0) {
sp->s_snmp_errno = SNMPERR_BAD_SENDTO;
sp->s_errno = errno;
snmp_set_detail(strerror(errno));
if (rp->callback) {
rp->callback(NETSNMP_CALLBACK_OP_SEND_FAILED, sp,
rp->pdu->reqid, rp->pdu, rp->cb_data);
remove_request(isp, orp, rp);
}
return -1;
} else {
netsnmp_get_monotonic_clock(&now);
tv = now;
rp->timeM = tv;
tv.tv_usec += rp->timeout;
tv.tv_sec += tv.tv_usec / 1000000L;
tv.tv_usec %= 1000000L;
rp->expireM = tv;
if (rp->callback)
rp->callback(NETSNMP_CALLBACK_OP_RESEND, sp,
rp->pdu->reqid, rp->pdu, rp->cb_data);
}
return 0;
}
void
snmp_sess_timeout(void *sessp)
{
struct session_list *slp = (struct session_list *) sessp;
netsnmp_session *sp;
struct snmp_internal_session *isp;
netsnmp_request_list *rp, *orp = NULL, *freeme = NULL;
struct timeval now;
snmp_callback callback;
void *magic;
struct snmp_secmod_def *sptr;
sp = slp->session;
isp = slp->internal;
if (!sp || !isp) {
DEBUGMSGTL(("sess_read", "timeout fail: closing...\n"));
return;
}
netsnmp_get_monotonic_clock(&now);
/*
* For each request outstanding, check to see if it has expired.
*/
for (rp = isp->requests; rp; rp = rp->next_request) {
if (freeme != NULL) {
/*
* frees rp's after the for loop goes on to the next_request
*/
free((char *) freeme);
freeme = NULL;
}
if ((timercmp(&rp->expireM, &now, <))) {
if ((sptr = find_sec_mod(rp->pdu->securityModel)) != NULL &&
sptr->pdu_timeout != NULL) {
/*
* call security model if it needs to know about this
*/
(*sptr->pdu_timeout) (rp->pdu);
}
/*
* this timer has expired
*/
if (rp->retries >= sp->retries) {
if (rp->callback) {
callback = rp->callback;
magic = rp->cb_data;
} else {
callback = sp->callback;
magic = sp->callback_magic;
}
/*
* No more chances, delete this entry
*/
if (callback) {
callback(NETSNMP_CALLBACK_OP_TIMED_OUT, sp,
rp->pdu->reqid, rp->pdu, magic);
}
remove_request(isp, orp, rp);
freeme = rp;
continue; /* don't update orp below */
} else {
if (snmp_resend_request(slp, orp, rp, TRUE)) {
break;
}
}
}
orp = rp;
}
if (freeme != NULL) {
free((char *) freeme);
freeme = NULL;
}
}
/*
* lexicographical compare two object identifiers.
* * Returns -1 if name1 < name2,
* * 0 if name1 = name2,
* * 1 if name1 > name2
* *
* * Caution: this method is called often by
* * command responder applications (ie, agent).
*/
int
snmp_oid_ncompare(const oid * in_name1,
size_t len1,
const oid * in_name2, size_t len2, size_t max_len)
{
register int len;
register const oid *name1 = in_name1;
register const oid *name2 = in_name2;
size_t min_len;
/*
* len = minimum of len1 and len2
*/
if (len1 < len2)
min_len = len1;
else
min_len = len2;
if (min_len > max_len)
min_len = max_len;
len = min_len;
/*
* find first non-matching OID
*/
while (len-- > 0) {
/*
* these must be done in seperate comparisons, since
* subtracting them and using that result has problems with
* subids > 2^31.
*/
if (*(name1) != *(name2)) {
if (*(name1) < *(name2))
return -1;
return 1;
}
name1++;
name2++;
}
if (min_len != max_len) {
/*
* both OIDs equal up to length of shorter OID
*/
if (len1 < len2)
return -1;
if (len2 < len1)
return 1;
}
return 0;
}
/**
* Lexicographically compare two object identifiers.
*
* @param[in] in_name1 Left hand side OID.
* @param[in] len1 Length of LHS OID.
* @param[in] in_name2 Rigth and side OID.
* @param[in] len2 Length of RHS OID.
*
* Caution: this method is called often by
* command responder applications (ie, agent).
*
* @return -1 if name1 < name2, 0 if name1 = name2, 1 if name1 > name2
*/
int
snmp_oid_compare(const oid * in_name1,
size_t len1, const oid * in_name2, size_t len2)
{
register int len;
register const oid *name1 = in_name1;
register const oid *name2 = in_name2;
/*
* len = minimum of len1 and len2
*/
if (len1 < len2)
len = len1;
else
len = len2;
/*
* find first non-matching OID
*/
while (len-- > 0) {
/*
* these must be done in seperate comparisons, since
* subtracting them and using that result has problems with
* subids > 2^31.
*/
if (*(name1) != *(name2)) {
if (*(name1) < *(name2))
return -1;
return 1;
}
name1++;
name2++;
}
/*
* both OIDs equal up to length of shorter OID
*/
if (len1 < len2)
return -1;
if (len2 < len1)
return 1;
return 0;
}
/**
* Lexicographically compare two object identifiers.
*
* @param[in] in_name1 Left hand side OID.
* @param[in] len1 Length of LHS OID.
* @param[in] in_name2 Rigth and side OID.
* @param[in] len2 Length of RHS OID.
* @param[out] offpt First offset at which the two OIDs differ.
*
* Caution: this method is called often by command responder applications (ie,
* agent).
*
* @return -1 if name1 < name2, 0 if name1 = name2, 1 if name1 > name2 and
* offpt = len where name1 != name2
*/
int
netsnmp_oid_compare_ll(const oid * in_name1, size_t len1, const oid * in_name2,
size_t len2, size_t *offpt)
{
register int len;
register const oid *name1 = in_name1;
register const oid *name2 = in_name2;
int initlen;
/*
* len = minimum of len1 and len2
*/
if (len1 < len2)
initlen = len = len1;
else
initlen = len = len2;
/*
* find first non-matching OID
*/
while (len-- > 0) {
/*
* these must be done in seperate comparisons, since
* subtracting them and using that result has problems with
* subids > 2^31.
*/
if (*(name1) != *(name2)) {
*offpt = initlen - len;
if (*(name1) < *(name2))
return -1;
return 1;
}
name1++;
name2++;
}
/*
* both OIDs equal up to length of shorter OID
*/
*offpt = initlen - len;
if (len1 < len2)
return -1;
if (len2 < len1)
return 1;
return 0;
}
/** Compares 2 OIDs to determine if they are equal up until the shortest length.
* @param in_name1 A pointer to the first oid.
* @param len1 length of the first OID (in segments, not bytes)
* @param in_name2 A pointer to the second oid.
* @param len2 length of the second OID (in segments, not bytes)
* @return 0 if they are equal, 1 if in_name1 is > in_name2, or -1 if <.
*/
int
snmp_oidtree_compare(const oid * in_name1,
size_t len1, const oid * in_name2, size_t len2)
{
int len = len1 < len2 ? len1 : len2;
return snmp_oid_compare(in_name1, len, in_name2, len);
}
int
snmp_oidsubtree_compare(const oid * in_name1,
size_t len1, const oid * in_name2, size_t len2)
{
int len = len1 < len2 ? len1 : len2;
return snmp_oid_compare(in_name1, len1, in_name2, len);
}
/** Compares 2 OIDs to determine if they are exactly equal.
* This should be faster than doing a snmp_oid_compare for different
* length OIDs, since the length is checked first and if != returns
* immediately. Might be very slighly faster if lengths are ==.
* @param in_name1 A pointer to the first oid.
* @param len1 length of the first OID (in segments, not bytes)
* @param in_name2 A pointer to the second oid.
* @param len2 length of the second OID (in segments, not bytes)
* @return 0 if they are equal, 1 if they are not.
*/
int
netsnmp_oid_equals(const oid * in_name1,
size_t len1, const oid * in_name2, size_t len2)
{
register const oid *name1 = in_name1;
register const oid *name2 = in_name2;
register int len = len1;
/*
* len = minimum of len1 and len2
*/
if (len1 != len2)
return 1;
/*
* Handle 'null' OIDs
*/
if (len1 == 0)
return 0; /* Two null OIDs are (trivially) the same */
if (!name1 || !name2)
return 1; /* Otherwise something's wrong, so report a non-match */
/*
* find first non-matching OID
*/
while (len-- > 0) {
/*
* these must be done in seperate comparisons, since
* subtracting them and using that result has problems with
* subids > 2^31.
*/
if (*(name1++) != *(name2++))
return 1;
}
return 0;
}
#ifndef NETSNMP_FEATURE_REMOVE_OID_IS_SUBTREE
/** Identical to netsnmp_oid_equals, except only the length up to len1 is compared.
* Functionally, this determines if in_name2 is equal or a subtree of in_name1
* @param in_name1 A pointer to the first oid.
* @param len1 length of the first OID (in segments, not bytes)
* @param in_name2 A pointer to the second oid.
* @param len2 length of the second OID (in segments, not bytes)
* @return 0 if one is a common prefix of the other.
*/
int
netsnmp_oid_is_subtree(const oid * in_name1,
size_t len1, const oid * in_name2, size_t len2)
{
if (len1 > len2)
return 1;
if (memcmp(in_name1, in_name2, len1 * sizeof(oid)))
return 1;
return 0;
}
#endif /* NETSNMP_FEATURE_REMOVE_OID_IS_SUBTREE */
/** Given two OIDs, determine the common prefix to them both.
* @param in_name1 A pointer to the first oid.
* @param len1 Length of the first oid.
* @param in_name2 A pointer to the second oid.
* @param len2 Length of the second oid.
* @return length of common prefix
* 0 if no common prefix, -1 on error.
*/
int
netsnmp_oid_find_prefix(const oid * in_name1, size_t len1,
const oid * in_name2, size_t len2)
{
int i;
size_t min_size;
if (!in_name1 || !in_name2 || !len1 || !len2)
return -1;
if (in_name1[0] != in_name2[0])
return 0; /* No match */
min_size = SNMP_MIN(len1, len2);
for(i = 0; i < (int)min_size; i++) {
if (in_name1[i] != in_name2[i])
return i; /* 'í' is the first differing subidentifier
So the common prefix is 0..(i-1), of length i */
}
return min_size; /* The shorter OID is a prefix of the longer, and
hence is precisely the common prefix of the two.
Return its length. */
}
#ifndef NETSNMP_DISABLE_MIB_LOADING
static int _check_range(struct tree *tp, long ltmp, int *resptr,
const char *errmsg)
{
char *cp = NULL;
char *temp = NULL;
int temp_len = 0;
int check = !netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID,
NETSNMP_DS_LIB_DONT_CHECK_RANGE);
if (check && tp && tp->ranges) {
struct range_list *rp = tp->ranges;
while (rp) {
if (rp->low <= ltmp && ltmp <= rp->high) break;
/* Allow four digits per range value */
temp_len += ((rp->low != rp->high) ? 27 : 15 );
rp = rp->next;
}
if (!rp) {
*resptr = SNMPERR_RANGE;
temp = (char *)malloc( temp_len+strlen(errmsg)+7);
if ( temp ) {
/* Append the Display Hint range information to the error message */
sprintf( temp, "%s :: {", errmsg );
cp = temp+(strlen(temp));
for ( rp = tp->ranges; rp; rp=rp->next ) {
if ( rp->low != rp->high )
sprintf( cp, "(%d..%d), ", rp->low, rp->high );
else
sprintf( cp, "(%d), ", rp->low );
cp += strlen(cp);
}
*(cp-2) = '}'; /* Replace the final comma with a '}' */
*(cp-1) = 0;
snmp_set_detail(temp);
free(temp);
}
return 0;
}
}
free(temp);
return 1;
}
#endif /* NETSNMP_DISABLE_MIB_LOADING */
/*
* Add a variable with the requested name to the end of the list of
* variables for this pdu.
*/
netsnmp_variable_list *
snmp_pdu_add_variable(netsnmp_pdu *pdu,
const oid * name,
size_t name_length,
u_char type, const void * value, size_t len)
{
return snmp_varlist_add_variable(&pdu->variables, name, name_length,
type, value, len);
}
/*
* Add a variable with the requested name to the end of the list of
* variables for this pdu.
*/
netsnmp_variable_list *
snmp_varlist_add_variable(netsnmp_variable_list ** varlist,
const oid * name,
size_t name_length,
u_char type, const void * value, size_t len)
{
netsnmp_variable_list *vars, *vtmp;
int rc;
if (varlist == NULL)
return NULL;
vars = SNMP_MALLOC_TYPEDEF(netsnmp_variable_list);
if (vars == NULL)
return NULL;
vars->type = type;
rc = snmp_set_var_value( vars, value, len );
if (( 0 != rc ) ||
(name != NULL && snmp_set_var_objid(vars, name, name_length))) {
snmp_free_var(vars);
return NULL;
}
/*
* put only qualified variable onto varlist
*/
if (*varlist == NULL) {
*varlist = vars;
} else {
for (vtmp = *varlist; vtmp->next_variable;
vtmp = vtmp->next_variable);
vtmp->next_variable = vars;
}
return vars;
}
/*
* Add a variable with the requested name to the end of the list of
* variables for this pdu.
* Returns:
* may set these error types :
* SNMPERR_RANGE - type, value, or length not found or out of range
* SNMPERR_VALUE - value is not correct
* SNMPERR_VAR_TYPE - type is not correct
* SNMPERR_BAD_NAME - name is not found
*
* returns 0 if success, error if failure.
*/
int
snmp_add_var(netsnmp_pdu *pdu,
const oid * name, size_t name_length, char type, const char *value)
{
char *st;
const char *cp;
char *ecp, *vp;
int result = SNMPERR_SUCCESS;
#ifndef NETSNMP_DISABLE_MIB_LOADING
int check = !netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID,
NETSNMP_DS_LIB_DONT_CHECK_RANGE);
int do_hint = !netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID,
NETSNMP_DS_LIB_NO_DISPLAY_HINT);
u_char *hintptr;
struct tree *tp;
struct enum_list *ep;
int itmp;
#endif /* NETSNMP_DISABLE_MIB_LOADING */
u_char *buf = NULL;
const u_char *buf_ptr = NULL;
size_t buf_len = 0, value_len = 0, tint;
in_addr_t atmp;
long ltmp;
#ifdef NETSNMP_WITH_OPAQUE_SPECIAL_TYPES
double dtmp;
float ftmp;
#endif /* NETSNMP_WITH_OPAQUE_SPECIAL_TYPES */
struct counter64 c64tmp;
#ifndef NETSNMP_DISABLE_MIB_LOADING
tp = get_tree(name, name_length, get_tree_head());
if (!tp || !tp->type || tp->type > TYPE_SIMPLE_LAST) {
check = 0;
}
if (!(tp && tp->hint))
do_hint = 0;
if (tp && type == '=') {
/*
* generic assignment - let the tree node decide value format
*/
switch (tp->type) {
case TYPE_INTEGER:
case TYPE_INTEGER32:
type = 'i';
break;
case TYPE_GAUGE:
case TYPE_UNSIGNED32:
type = 'u';
break;
case TYPE_UINTEGER:
type = '3';
break;
case TYPE_COUNTER:
type = 'c';
break;
case TYPE_COUNTER64:
type = 'C';
break;
case TYPE_TIMETICKS:
type = 't';
break;
case TYPE_OCTETSTR:
type = 's';
break;
case TYPE_BITSTRING:
type = 'b';
break;
case TYPE_IPADDR:
type = 'a';
break;
case TYPE_OBJID:
type = 'o';
break;
}
}
#endif /* NETSNMP_DISABLE_MIB_LOADING */
switch (type) {
case 'i':
#ifndef NETSNMP_DISABLE_MIB_LOADING
if (check && tp->type != TYPE_INTEGER
&& tp->type != TYPE_INTEGER32) {
value = "INTEGER";
result = SNMPERR_VALUE;
goto type_error;
}
#endif /* NETSNMP_DISABLE_MIB_LOADING */
if (!*value)
goto fail;
ltmp = strtol(value, &ecp, 10);
if (*ecp) {
#ifndef NETSNMP_DISABLE_MIB_LOADING
ep = tp ? tp->enums : NULL;
while (ep) {
if (strcmp(value, ep->label) == 0) {
ltmp = ep->value;
break;
}
ep = ep->next;
}
if (!ep) {
#endif /* NETSNMP_DISABLE_MIB_LOADING */
result = SNMPERR_RANGE; /* ?? or SNMPERR_VALUE; */
snmp_set_detail(value);
break;
#ifndef NETSNMP_DISABLE_MIB_LOADING
}
#endif /* NETSNMP_DISABLE_MIB_LOADING */
}
#ifndef NETSNMP_DISABLE_MIB_LOADING
if (!_check_range(tp, ltmp, &result, value))
break;
#endif /* NETSNMP_DISABLE_MIB_LOADING */
snmp_pdu_add_variable(pdu, name, name_length, ASN_INTEGER,
<mp, sizeof(ltmp));
break;
case 'u':
#ifndef NETSNMP_DISABLE_MIB_LOADING
if (check && tp->type != TYPE_GAUGE && tp->type != TYPE_UNSIGNED32) {
value = "Unsigned32";
result = SNMPERR_VALUE;
goto type_error;
}
#endif /* NETSNMP_DISABLE_MIB_LOADING */
ltmp = strtoul(value, &ecp, 10);
if (*value && !*ecp)
snmp_pdu_add_variable(pdu, name, name_length, ASN_UNSIGNED,
<mp, sizeof(ltmp));
else
goto fail;
break;
case '3':
#ifndef NETSNMP_DISABLE_MIB_LOADING
if (check && tp->type != TYPE_UINTEGER) {
value = "UInteger32";
result = SNMPERR_VALUE;
goto type_error;
}
#endif /* NETSNMP_DISABLE_MIB_LOADING */
ltmp = strtoul(value, &ecp, 10);
if (*value && !*ecp)
snmp_pdu_add_variable(pdu, name, name_length, ASN_UINTEGER,
<mp, sizeof(ltmp));
else
goto fail;
break;
case 'c':
#ifndef NETSNMP_DISABLE_MIB_LOADING
if (check && tp->type != TYPE_COUNTER) {
value = "Counter32";
result = SNMPERR_VALUE;
goto type_error;
}
#endif /* NETSNMP_DISABLE_MIB_LOADING */
ltmp = strtoul(value, &ecp, 10);
if (*value && !*ecp)
snmp_pdu_add_variable(pdu, name, name_length, ASN_COUNTER,
<mp, sizeof(ltmp));
else
goto fail;
break;
case 'C':
#ifndef NETSNMP_DISABLE_MIB_LOADING
if (check && tp->type != TYPE_COUNTER64) {
value = "Counter64";
result = SNMPERR_VALUE;
goto type_error;
}
#endif /* NETSNMP_DISABLE_MIB_LOADING */
if (read64(&c64tmp, value))
snmp_pdu_add_variable(pdu, name, name_length, ASN_COUNTER64,
&c64tmp, sizeof(c64tmp));
else
goto fail;
break;
case 't':
#ifndef NETSNMP_DISABLE_MIB_LOADING
if (check && tp->type != TYPE_TIMETICKS) {
value = "Timeticks";
result = SNMPERR_VALUE;
goto type_error;
}
#endif /* NETSNMP_DISABLE_MIB_LOADING */
ltmp = strtoul(value, &ecp, 10);
if (*value && !*ecp)
snmp_pdu_add_variable(pdu, name, name_length, ASN_TIMETICKS,
<mp, sizeof(long));
else
goto fail;
break;
case 'a':
#ifndef NETSNMP_DISABLE_MIB_LOADING
if (check && tp->type != TYPE_IPADDR) {
value = "IpAddress";
result = SNMPERR_VALUE;
goto type_error;
}
#endif /* NETSNMP_DISABLE_MIB_LOADING */
atmp = inet_addr(value);
if (atmp != (in_addr_t) -1 || !strcmp(value, "255.255.255.255"))
snmp_pdu_add_variable(pdu, name, name_length, ASN_IPADDRESS,
&atmp, sizeof(atmp));
else
goto fail;
break;
case 'o':
#ifndef NETSNMP_DISABLE_MIB_LOADING
if (check && tp->type != TYPE_OBJID) {
value = "OBJECT IDENTIFIER";
result = SNMPERR_VALUE;
goto type_error;
}
#endif /* NETSNMP_DISABLE_MIB_LOADING */
if ((buf = (u_char *)malloc(sizeof(oid) * MAX_OID_LEN)) == NULL) {
result = SNMPERR_MALLOC;
} else {
tint = MAX_OID_LEN;
if (snmp_parse_oid(value, (oid *) buf, &tint)) {
snmp_pdu_add_variable(pdu, name, name_length, ASN_OBJECT_ID,
buf, sizeof(oid) * tint);
} else {
result = snmp_errno; /*MTCRITICAL_RESOURCE */
}
}
break;
case 's':
case 'x':
case 'd':
#ifndef NETSNMP_DISABLE_MIB_LOADING
if (check && tp->type != TYPE_OCTETSTR && tp->type != TYPE_BITSTRING) {
value = "OCTET STRING";
result = SNMPERR_VALUE;
goto type_error;
}
if ('s' == type && do_hint && !parse_octet_hint(tp->hint, value, &hintptr, &itmp)) {
if (_check_range(tp, itmp, &result, "Value does not match DISPLAY-HINT")) {
snmp_pdu_add_variable(pdu, name, name_length, ASN_OCTET_STR,
hintptr, itmp);
}
SNMP_FREE(hintptr);
hintptr = buf;
break;
}
#endif /* NETSNMP_DISABLE_MIB_LOADING */
if (type == 'd') {
if (!snmp_decimal_to_binary
(&buf, &buf_len, &value_len, 1, value)) {
result = SNMPERR_VALUE;
snmp_set_detail(value);
break;
}
buf_ptr = buf;
} else if (type == 'x') {
if (!snmp_hex_to_binary(&buf, &buf_len, &value_len, 1, value)) {
result = SNMPERR_VALUE;
snmp_set_detail(value);
break;
}
buf_ptr = buf;
} else if (type == 's') {
buf_ptr = (const u_char *)value;
value_len = strlen(value);
}
#ifndef NETSNMP_DISABLE_MIB_LOADING
if (!_check_range(tp, value_len, &result, "Bad string length"))
break;
#endif /* NETSNMP_DISABLE_MIB_LOADING */
snmp_pdu_add_variable(pdu, name, name_length, ASN_OCTET_STR,
buf_ptr, value_len);
break;
case 'n':
snmp_pdu_add_variable(pdu, name, name_length, ASN_NULL, NULL, 0);
break;
case 'b':
#ifndef NETSNMP_DISABLE_MIB_LOADING
if (check && (tp->type != TYPE_BITSTRING || !tp->enums)) {
value = "BITS";
result = SNMPERR_VALUE;
goto type_error;
}
#endif /* NETSNMP_DISABLE_MIB_LOADING */
tint = 0;
if ((buf = (u_char *) malloc(256)) == NULL) {
result = SNMPERR_MALLOC;
break;
} else {
buf_len = 256;
memset(buf, 0, buf_len);
}
#ifndef NETSNMP_DISABLE_MIB_LOADING
for (ep = tp ? tp->enums : NULL; ep; ep = ep->next) {
if (ep->value / 8 >= (int) tint) {
tint = ep->value / 8 + 1;
}
}
#endif /* NETSNMP_DISABLE_MIB_LOADING */
vp = strdup(value);
if (!vp) {
SNMP_FREE(buf);
goto fail;
}
for (cp = strtok_r(vp, " ,\t", &st); cp; cp = strtok_r(NULL, " ,\t", &st)) {
int ix, bit;
ltmp = strtoul(cp, &ecp, 0);
if (*ecp != 0) {
#ifndef NETSNMP_DISABLE_MIB_LOADING
for (ep = tp ? tp->enums : NULL; ep != NULL; ep = ep->next) {
if (strcmp(ep->label, cp) == 0) {
break;
}
}
if (ep != NULL) {
ltmp = ep->value;
} else {
#endif /* NETSNMP_DISABLE_MIB_LOADING */
result = SNMPERR_RANGE; /* ?? or SNMPERR_VALUE; */
snmp_set_detail(cp);
SNMP_FREE(buf);
SNMP_FREE(vp);
goto out;
#ifndef NETSNMP_DISABLE_MIB_LOADING
}
#endif /* NETSNMP_DISABLE_MIB_LOADING */
}
ix = ltmp / 8;
if (ix >= (int) tint) {
tint = ix + 1;
}
if (ix >= (int)buf_len && !snmp_realloc(&buf, &buf_len)) {
result = SNMPERR_MALLOC;
break;
}
bit = 0x80 >> ltmp % 8;
buf[ix] |= bit;
}
SNMP_FREE(vp);
snmp_pdu_add_variable(pdu, name, name_length, ASN_OCTET_STR,
buf, tint);
break;
#ifdef NETSNMP_WITH_OPAQUE_SPECIAL_TYPES
case 'U':
if (read64(&c64tmp, value))
snmp_pdu_add_variable(pdu, name, name_length, ASN_OPAQUE_U64,
&c64tmp, sizeof(c64tmp));
else
goto fail;
break;
case 'I':
if (read64(&c64tmp, value))
snmp_pdu_add_variable(pdu, name, name_length, ASN_OPAQUE_I64,
&c64tmp, sizeof(c64tmp));
else
goto fail;
break;
case 'F':
if (sscanf(value, "%f", &ftmp) == 1)
snmp_pdu_add_variable(pdu, name, name_length, ASN_OPAQUE_FLOAT,
&ftmp, sizeof(ftmp));
else
goto fail;
break;
case 'D':
if (sscanf(value, "%lf", &dtmp) == 1)
snmp_pdu_add_variable(pdu, name, name_length, ASN_OPAQUE_DOUBLE,
&dtmp, sizeof(dtmp));
else
goto fail;
break;
#endif /* NETSNMP_WITH_OPAQUE_SPECIAL_TYPES */
default:
result = SNMPERR_VAR_TYPE;
buf = (u_char *)calloc(1, 4);
if (buf != NULL) {
sprintf((char *)buf, "\"%c\"", type);
snmp_set_detail((char *)buf);
}
break;
}
SNMP_FREE(buf);
SET_SNMP_ERROR(result);
return result;
#ifndef NETSNMP_DISABLE_MIB_LOADING
type_error:
{
char error_msg[256];
char undef_msg[32];
const char *var_type;
switch (tp->type) {
case TYPE_OBJID:
var_type = "OBJECT IDENTIFIER";
break;
case TYPE_OCTETSTR:
var_type = "OCTET STRING";
break;
case TYPE_INTEGER:
var_type = "INTEGER";
break;
case TYPE_NETADDR:
var_type = "NetworkAddress";
break;
case TYPE_IPADDR:
var_type = "IpAddress";
break;
case TYPE_COUNTER:
var_type = "Counter32";
break;
case TYPE_GAUGE:
var_type = "Gauge32";
break;
case TYPE_TIMETICKS:
var_type = "Timeticks";
break;
case TYPE_OPAQUE:
var_type = "Opaque";
break;
case TYPE_NULL:
var_type = "Null";
break;
case TYPE_COUNTER64:
var_type = "Counter64";
break;
case TYPE_BITSTRING:
var_type = "BITS";
break;
case TYPE_NSAPADDRESS:
var_type = "NsapAddress";
break;
case TYPE_UINTEGER:
var_type = "UInteger";
break;
case TYPE_UNSIGNED32:
var_type = "Unsigned32";
break;
case TYPE_INTEGER32:
var_type = "Integer32";
break;
default:
sprintf(undef_msg, "TYPE_%d", tp->type);
var_type = undef_msg;
}
snprintf(error_msg, sizeof(error_msg),
"Type of attribute is %s, not %s", var_type, value);
error_msg[ sizeof(error_msg)-1 ] = 0;
result = SNMPERR_VAR_TYPE;
snmp_set_detail(error_msg);
goto out;
}
#endif /* NETSNMP_DISABLE_MIB_LOADING */
fail:
result = SNMPERR_VALUE;
snmp_set_detail(value);
out:
SET_SNMP_ERROR(result);
return result;
}
/*
* returns NULL or internal pointer to session
* use this pointer for the other snmp_sess* routines,
* which guarantee action will occur ONLY for this given session.
*/
void *
snmp_sess_pointer(netsnmp_session * session)
{
struct session_list *slp;
snmp_res_lock(MT_LIBRARY_ID, MT_LIB_SESSION);
for (slp = Sessions; slp; slp = slp->next) {
if (slp->session == session) {
break;
}
}
snmp_res_unlock(MT_LIBRARY_ID, MT_LIB_SESSION);
if (slp == NULL) {
snmp_errno = SNMPERR_BAD_SESSION; /*MTCRITICAL_RESOURCE */
return (NULL);
}
return ((void *) slp);
}
/*
* Input : an opaque pointer, returned by snmp_sess_open.
* returns NULL or pointer to session.
*/
netsnmp_session *
snmp_sess_session(void *sessp)
{
struct session_list *slp = (struct session_list *) sessp;
if (slp == NULL)
return (NULL);
return (slp->session);
}
/**
* Look up a session that already may have been closed.
*
* @param sessp Opaque pointer, returned by snmp_sess_open.
*
* @return Pointer to session upon success or NULL upon failure.
*
* @see snmp_sess_session()
*/
netsnmp_session *
snmp_sess_session_lookup(void *sessp)
{
struct session_list *slp;
snmp_res_lock(MT_LIBRARY_ID, MT_LIB_SESSION);
for (slp = Sessions; slp; slp = slp->next) {
if (slp == sessp) {
break;
}
}
snmp_res_unlock(MT_LIBRARY_ID, MT_LIB_SESSION);
return (netsnmp_session *)slp;
}
/*
* returns NULL or internal pointer to session
* use this pointer for the other snmp_sess* routines,
* which guarantee action will occur ONLY for this given session.
*/
netsnmp_session *
snmp_sess_lookup_by_name(const char *paramName)
{
struct session_list *slp;
snmp_res_lock(MT_LIBRARY_ID, MT_LIB_SESSION);
for (slp = Sessions; slp; slp = slp->next) {
if (NULL == slp->session->paramName)
continue;
if (strcmp(paramName, slp->session->paramName) == 0)
break;
}
snmp_res_unlock(MT_LIBRARY_ID, MT_LIB_SESSION);
if (slp == NULL)
return NULL;
return slp->session;
}
/*
* snmp_sess_transport: takes an opaque pointer (as returned by
* snmp_sess_open or snmp_sess_pointer) and returns the corresponding
* netsnmp_transport pointer (or NULL if the opaque pointer does not correspond
* to an active internal session).
*/
netsnmp_transport *
snmp_sess_transport(void *sessp)
{
struct session_list *slp = (struct session_list *) sessp;
if (slp == NULL) {
return NULL;
} else {
return slp->transport;
}
}
/*
* snmp_sess_transport_set: set the transport pointer for the opaque
* session pointer sp.
*/
void
snmp_sess_transport_set(void *sp, netsnmp_transport *t)
{
struct session_list *slp = (struct session_list *) sp;
if (slp != NULL) {
slp->transport = t;
}
}
/*
* snmp_duplicate_objid: duplicates (mallocs) an objid based on the
* input objid
*/
oid *
snmp_duplicate_objid(const oid * objToCopy, size_t objToCopyLen)
{
oid *returnOid;
if (objToCopy != NULL && objToCopyLen != 0) {
returnOid = (oid *) malloc(objToCopyLen * sizeof(oid));
if (returnOid) {
memcpy(returnOid, objToCopy, objToCopyLen * sizeof(oid));
}
} else
returnOid = NULL;
return returnOid;
}
#ifndef NETSNMP_FEATURE_REMOVE_STATISTICS
/*
* generic statistics counter functions
*/
static u_int statistics[NETSNMP_STAT_MAX_STATS];
u_int
snmp_increment_statistic(int which)
{
if (which >= 0 && which < NETSNMP_STAT_MAX_STATS) {
statistics[which]++;
return statistics[which];
}
return 0;
}
u_int
snmp_increment_statistic_by(int which, int count)
{
if (which >= 0 && which < NETSNMP_STAT_MAX_STATS) {
statistics[which] += count;
return statistics[which];
}
return 0;
}
u_int
snmp_get_statistic(int which)
{
if (which >= 0 && which < NETSNMP_STAT_MAX_STATS)
return statistics[which];
return 0;
}
void
snmp_init_statistics(void)
{
memset(statistics, 0, sizeof(statistics));
}
#endif /* NETSNMP_FEATURE_REMOVE_STATISTICS */
/** @} */
| [
"[email protected]"
] | |
70a1f47f88bc7003c9dd6f48b035dbd9904188cb | 2a1dafebb0adfc7043166d6cb1f9cd9fad0ea454 | /past.c | 65a8ef840ba334d25c48068e9d2955b9e973b540 | [] | no_license | dalidossodautais/malloc | dd4cbd3e8c6526692d43c07df9ce44c928e50a9f | 429c0e3333ad12a1fa9cea2fc7533022327984e9 | refs/heads/master | 2021-05-08T10:53:17.902450 | 2018-02-01T16:40:25 | 2018-02-01T16:40:25 | 119,863,354 | 0 | 0 | null | null | null | null | UTF-8 | C | false | false | 2,321 | c | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* malloc.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ddosso-d <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/01/08 17:05:30 by ddosso-d #+# #+# */
/* Updated: 2018/01/08 17:05:33 by ddosso-d ### ########.fr */
/* */
/* ************************************************************************** */
#include "malloc.h"
void fill_empty(t_page *new, size_t size)
{
size_t i;
if (size <= SMALL)
{
new->empty[0] = (START | FILLED);
i = 1;
while (i < size)
new->empty[i++] = FILLED;
while (i < new->space)
new->empty[i++] = EMPTY;
}
}
void *create_page(size_t size)
{
t_page *tmp;
t_page *new;
if (!(new = (t_page *)mmap(0, sizeof(t_page), PROT_WRITE,
MAP_SHARED | MAP_ANONYMOUS, -1, 0)))
return (0);
new->space = SPACE(size);
if (!(new->mem = (void *)mmap(0, size, PROT_WRITE,
MAP_SHARED | MAP_ANONYMOUS, -1, 0)))
return (0);
new->next = 0;
fill_empty(new, size);
tmp = (t_page *)g_page;
while (tmp && tmp->next)
tmp = tmp->next;
if (!g_page)
g_page = new;
else
tmp->next = new;
return (new->mem);
}
void *can_enter(t_page *page, size_t size)
{
size_t i;
size_t j;
i = 0;
while (i < page->space)
{
j = 0;
while (i + j < page->space && j < size && page->empty[i + j] == FILLED)
++j;
if (j == size)
break ;
i += j + 1;
}
if (j == size)
return (0);
page->empty[i + j++] = (START | FILLED);
j = 1;
while (j < size)
page->empty[i + j++] = FILLED;
return (page->mem + i);
}
void *malloc(size_t size)
{
t_page *page;
void *mem;
if (!size)
return (0);
page = (t_page *)g_page;
while (page)
{
if (size < SMALL && page->space == SPACE(size) &&
(mem = can_enter(page, size)))
return (mem);
page = page->next;
}
return (create_page(size));
}
| [
"[email protected]"
] | |
d29b519d1cd955d92cc0cd3240d8c7b8e667349f | d37fb3fe6d64237ce71ac11a64314689063cf56e | /Project/Algorithms/Second/Stack_Linked_list.c | e0c26a82b957e805b804040f7ce343d60ff135a8 | [] | no_license | designer-jqy/Project | 36c518daa5e0f92faa544e4df69c1cd1c0176766 | db2551f9f51124ab92d00e8b35c446bc68149535 | refs/heads/master | 2022-02-16T09:24:50.647147 | 2022-01-28T15:25:29 | 2022-01-28T15:25:29 | 225,270,252 | 3 | 0 | null | null | null | null | UTF-8 | C | false | false | 951 | c | #include<stdio.h>
#include<stdlib.h>
#define TYPE char
#define ITERATION 8
typedef struct Node{
TYPE item;
struct Node *next;
}node, *nodeptr;
struct Linked_list{
nodeptr top;
int num;
}Linked;
void push(node *s, struct Linked_list *S, TYPE *item){
s->item = *item;
s->next = S->top;
S->top = s;
S->num++;
}
void pop(struct Linked_list *S){
nodeptr old_s;
old_s = S->top;
S->top = old_s->next;
printf("%c\n", old_s->item);
free(old_s);
S->num--;
}
int main(){
TYPE item;
struct Linked_list S;
node *sptr;
node s;
S.top = NULL;
S.num = 0;
printf("Please input the thing:");
for(int i = 0; i < ITERATION; i++){
sptr = (nodeptr)malloc(sizeof(node));
scanf("%c", &item);
push(sptr, &S, &item);
}
printf("The num:%d\n", S.num);
for(int j = 0; j < ITERATION; j++){
pop(&S);
}
printf("The num:%d\n", S.num);
// isEmpty();
// size();
return 0;
} | [
"[email protected]"
] | |
bc6826dde7a0140178367a37376466a132074586 | ea1a0784237dee933f071b9e79254730844ac8c5 | /程序/ks103/KS103/BSP/bsp.c | d9dea8289b96768e9142617b69692479ea5e1335 | [] | no_license | renshangrenyjl/TITRrc | 7931c8695b4448d407a7d541aef7fc9e888bad47 | d7c5089ff0cf43d675aeb66572e49904420adb5f | refs/heads/master | 2023-01-22T06:54:54.489352 | 2020-11-29T01:27:17 | 2020-11-29T01:27:17 | 316,856,844 | 0 | 0 | null | null | null | null | GB18030 | C | false | false | 21,447 | c | #include "stm32f4xx.h"
/*********************************************************************************************************
BSP简介:
板级支持包(BSP)是介于主板硬件和操作系统中驱动层程序之间的一层,一般认为它属于操作系统一部分,主要是
实现对操作系统的支持,为上层的驱动程序提供访问硬件设备寄存器的函数包,使之能够更好的运行于硬件主板。
在嵌入式系统软件的组成中,就有BSP。BSP是相对于操作系统而言的,不同的操作系统对应于不同定义形式的BSP,
例如VxWorks的BSP和Linux的BSP相对于某一CPU来说尽管实现的功能一样,可是写法和接口定义是完全不同的,所以写BSP
一定要按照该系统BSP的定义形式来写(BSP的编程过程大多数是在某一个成型的BSP模板上进行修改)。这样才能与上层
OS保持正确的接口,良好的支持上层OS。
作用:
建立让操作系统运行的基本环境
1、初始化CPU内部寄存器
2、设定RAM工作时序
3、时钟驱动及中断控制器驱动
4、串口驱动
完善操作系统运行的环境
1、完善高速缓存和内存管理单元的驱动
2、指定程序起始运行位置
3、完善中断管理
4、完善系统总线驱动
*********************************************************************************************************/
/*********************************************************************************************************
* 宏定义
*********************************************************************************************************/
/*********************************************************************************************************
* 结构体变量
*********************************************************************************************************/
/*********************************************************************************************************
* 函数声明
*********************************************************************************************************/
char *itoa(int value, char *string, int radix);
void USART_OUT(USART_TypeDef* USARTx, uint8_t *Data,...);
void RCC_Configuration(void);
void GPIO_Configuration(void);
void EXTI_Configuration(void);
void NVIC_Configuration(void);
void USART1_Configuration(void);
void USART2_Configuration(void);
void USART3_Configuration(void);
void TIM3_Configuration(void);
/*********************************************************************************************************
* 程序配置
*********************************************************************************************************/
void BSP_Init(void)
{
RCC_Configuration();
GPIO_Configuration();
EXTI_Configuration();
NVIC_Configuration();
USART1_Configuration(); //如果串口打印功能使用了(如开机字符) 但是硬件没有配置的话 板子会死掉
USART3_Configuration();
TIM3_Configuration();
NVIC_Configuration();
}
/*******************************************************************************
* Function Name : RCC_Configuration
* Description : Configures the different system clocks.
* Input : None
* Output : None
* Return : None
*******************************************************************************/
void RCC_Configuration(void)
{
SystemInit();
/*io口时钟配置 168MHz*/
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA| RCC_AHB1Periph_GPIOB| RCC_AHB1Periph_GPIOC| RCC_AHB1Periph_GPIOD|
RCC_AHB1Periph_GPIOE, ENABLE);
/*APB2 84MHz 配置timer时会倍频为168mhz,具体有哪些在此时钟上可跳进去查看*/
RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1| RCC_APB2Periph_TIM1| RCC_APB2Periph_TIM8|
RCC_APB2Periph_TIM9| RCC_APB2Periph_SYSCFG, ENABLE);
/*APB1 42MHz 配置为timer时会倍频为84MHz*/
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2| RCC_APB1Periph_TIM3| RCC_APB1Periph_TIM4| RCC_APB1Periph_TIM5|
RCC_APB1Periph_TIM7| RCC_APB1Periph_TIM12| RCC_APB1Periph_USART2|
RCC_APB1Periph_USART3| RCC_APB1Periph_UART4| RCC_APB1Periph_CAN1,ENABLE);
}
/*******************************************************************************
* Function Name : GPIO_Configuration
* Description : None
* Input : None
* Output : None
* Return : None
*******************************************************************************/
void GPIO_Configuration(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
// GPIO_InitStructure.GPIO_Pin = GPIO_Pin_All; //选择GPIOA全部的16个拐脚
// GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN; //I/O口配置为输入操作模式
// GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz; //速度100M
// GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP; //GPIO_PuPd_DOWN 分别是配置I/O口的上拉和下拉
// GPIO_Init(GPIOA, &GPIO_InitStructure);
// GPIO_InitStructure.GPIO_Pin = GPIO_Pin_12; //选择GPIOA全部的16个拐脚
// GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN; //I/O口配置为输入操作模式
// GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz; //速度100M
// GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP; //GPIO_PuPd_DOWN 分别是配置I/O口的上拉和下拉
// GPIO_Init(GPIOB, &GPIO_InitStructure);
// GPIO_InitStructure.GPIO_Pin = GPIO_Pin_All; //选择GPIO-B12口
// GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT; //I/O口配置为输出操作模式
// GPIO_InitStructure.GPIO_OType = GPIO_OType_PP; //配置为推挽输出类型
// GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz; //速度100M
// GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL; //I/O口无上拉和下拉(高阻态)
// GPIO_Init(GPIOD, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_11; //选择GPIO-B12口
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN; //I/O口配置为输出操作模式
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP; //配置为推挽输出类型
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz; //速度100M
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL; //I/O口无上拉和下拉(高阻态)
GPIO_Init(GPIOB, &GPIO_InitStructure);
// GPIO_InitStructure.GPIO_Pin = GPIO_Pin_13; //选择GPIO-B13口
// GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT; //I/O口配置为输出操作模式
// GPIO_InitStructure.GPIO_OType = GPIO_OType_OD; //配置开漏输出类型
// GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz; //速度100M
// GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL; //I/O口无上拉和下拉(高阻态)
// GPIO_Init(GPIOB, &GPIO_InitStructure);
//
// GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0|GPIO_Pin_1; //选择GPIO-C0和C1口
// GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT; //I/O口配置为输出操作模式
// GPIO_InitStructure.GPIO_OType = GPIO_OType_PP; //配置开漏输出类型
// GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; //速度50M 2,25,50,100四种选择
// GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL; //I/O口无上拉和下拉(高阻态)
// GPIO_Init(GPIOC, &GPIO_InitStructure);
}
/*******************************************************************************
* Function Name : USART1_Configuration
* Description : None
* Input : None
* Output : None
* Return : None
*******************************************************************************/
void USART1_Configuration(void)
{
GPIO_InitTypeDef GPIO_InitStructure; //定义GPIO初始化结构体
USART_InitTypeDef USART_InitStructure; //定义USART初始化结构体
/*时钟配置不需要配置AFIO 只要配置为复用功能即可*/
GPIO_PinAFConfig(GPIOA,GPIO_PinSource9,GPIO_AF_USART1); //配置PA9复用连接到USART1
GPIO_PinAFConfig(GPIOA,GPIO_PinSource10,GPIO_AF_USART1); //配置PA10复用连接到USART1
GPIO_InitStructure.GPIO_Pin=GPIO_Pin_9; //设置初始化GPIO为PIN9
GPIO_InitStructure.GPIO_Speed=GPIO_Speed_100MHz; //设置GPIO的速度为50MHz
GPIO_InitStructure.GPIO_Mode=GPIO_Mode_AF; //设置GPIO模式为复用模式
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP; //设置GPIO输出类型为推挽输出
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP; //设置GPIO为连接上拉电阻
GPIO_Init(GPIOA,&GPIO_InitStructure); //初始化GPIOA的PIN9
GPIO_InitStructure.GPIO_Pin=GPIO_Pin_10; //设置初始化GPIO为PIN10
GPIO_InitStructure.GPIO_Mode=GPIO_Mode_AF; //设置GPIO的模式为复用模式
GPIO_Init(GPIOA,&GPIO_InitStructure); //初始化GPIOA的PIN10
USART_InitStructure.USART_BaudRate=9600; //设置USART的波特率为115200
USART_InitStructure.USART_Parity=USART_Parity_No; //设置USART的校验位为None
USART_InitStructure.USART_WordLength=USART_WordLength_8b; //设置USART的数据位为8bit
USART_InitStructure.USART_StopBits=USART_StopBits_1; //设置USART的停止位为1
USART_InitStructure.USART_HardwareFlowControl=USART_HardwareFlowControl_None; //失能硬件流控制
USART_InitStructure.USART_Mode=USART_Mode_Rx|USART_Mode_Tx; //设置USART的模式为发送接收模式
USART_Init(USART1, &USART_InitStructure);
USART_ITConfig(USART1, USART_IT_RXNE, ENABLE);
USART_Cmd(USART1, ENABLE);
}
/*******************************************************************************
* Function Name : USART2_Configuration
* Description : None
* Input : None
* Output : None
* Return : None
*******************************************************************************/
void USART2_Configuration(void)
{
}
/*******************************************************************************
* Function Name : USART3_Configuration
* Description : 陀螺仪通信
* Input : None
* Output : None
* Return : None
*******************************************************************************/
void USART3_Configuration(void)
{
}
/*******************************************************************************
* Function Name : UART4_Configuration
* Description : None
* Input : None
* Output : None
* Return : None
*******************************************************************************/
void UART4_Configuration(void)
{
}
/*******************************************************************************
* Function Name : TIM1_Configuration
* Description : None
* Input : None
* Output : None
* Return : None
*******************************************************************************/
void TIM1_Configuration(void)
{
}
/*******************************************************************************
* Function Name : TIM2_Configuration
* Description : None
* Input : None
* Output : None
* Return : None
*******************************************************************************/
void TIM2_Configuration(void)
{
}
/*******************************************************************************
* Function Name : TIM3_Configuration
* Description : None
* Input : None
* Output : None
* Return : None
*******************************************************************************/
void TIM3_Configuration(void)
{
}
/*******************************************************************************
* Function Name : TIM4_Configuration
* Input : None
* Output : None
* Return : None
*******************************************************************************/
void TIM4_Configuration(void)
{
// TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
// TIM_TimeBaseStructure.TIM_Period = 4000; //2 == 1ms 最大计数
// TIM_TimeBaseStructure.TIM_Prescaler = (42000-1); //tim5为84MHz 分频 这个数能大不小
// TIM_TimeBaseStructure.TIM_ClockDivision = 0; //时钟分割
// TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up; //向上计数
// TIM_TimeBaseInit(TIM4, &TIM_TimeBaseStructure);
//
// TIM_ClearFlag(TIM4,TIM_FLAG_Update);
// TIM_ITConfig(TIM4,TIM_IT_Update,ENABLE);
// TIM_Cmd(TIM4, ENABLE);
}
/*******************************************************************************
* Function Name : TIM5_Configuration
* Description : None
* Input : None
* Output : None
* Return : None
*******************************************************************************/
void TIM5_Configuration(void)
{
// TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
// TIM_TimeBaseStructure.TIM_Period = 4000; //2 == 1ms 最大计数
// TIM_TimeBaseStructure.TIM_Prescaler = (42000-1); //tim5为84MHz 分频 这个数能大不小
// TIM_TimeBaseStructure.TIM_ClockDivision = 0; //时钟分割
// TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up; //向上计数
// TIM_TimeBaseInit(TIM5, &TIM_TimeBaseStructure);
//
// TIM_ClearFlag(TIM5,TIM_FLAG_Update);
// TIM_ITConfig(TIM5,TIM_IT_Update,ENABLE);
// TIM_Cmd(TIM5, ENABLE);
}
/*******************************************************************************
* Function Name : TIM7_Configuration
* Description : None
* Input : None
* Output : None
* Return : None
*******************************************************************************/
void TIM7_Configuration(void)
{
}
/*******************************************************************************
* Function Name : TIM8_Configuration
* Description : None
* Input : None
* Output : None
* Return : None
*******************************************************************************/
void TIM8_Configuration(void)
{
}
/*******************************************************************************
* Function Name : TIM9_Configuration
* Description : None
* Input : None
* Output : None
* Return : None
*******************************************************************************/
void TIM9_Configuration(void)
{
}
/*******************************************************************************
* Function Name : TIM12_Configuration
* Description : None
* Input : None
* Output : None
* Return : None
*******************************************************************************/
void TIM12_Configuration(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
TIM_OCInitTypeDef TIM_OCInitStructure;
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
/* Connect TIM pins to AF3 */
GPIO_PinAFConfig(GPIOB, GPIO_PinSource14, GPIO_AF_TIM12); // CH1 //通道1
// GPIO_PinAFConfig(GPIOA, GPIO_PinSource3, GPIO_AF_TIM2); // CH2 //通道2
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_12;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP ;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz;
GPIO_Init(GPIOB, &GPIO_InitStructure); //以上是对于需要用到的I/O口的配置
TIM_TimeBaseStructure.TIM_Period = 10000; //计数上限
TIM_TimeBaseStructure.TIM_Prescaler = (35-1); //定时器时钟频率分频
TIM_TimeBaseStructure.TIM_ClockDivision = 0; //时钟分割,一般写0
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up; //设置为向上计数模式
TIM_TimeBaseInit(TIM12, &TIM_TimeBaseStructure);
TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable; //比较寄存器使能
TIM_OCInitStructure.TIM_Pulse = 9500; //比较寄存器装载值
TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High; //输出比较极性高
//TIM_OCPolarity_Low //输出比较极性低
TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1; //PWM模式1
TIM_OC1Init(TIM12, &TIM_OCInitStructure); //通道3使能
TIM_OC1PreloadConfig(TIM12, TIM_OCPreload_Enable);
// TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM2;
// TIM_OC4Init(TIM2, &TIM_OCInitStructure); //通道4使能
// TIM_OC4PreloadConfig(TIM2, TIM_OCPreload_Enable);
TIM_ARRPreloadConfig(TIM12, ENABLE); //使用定时器的比较输出功能时配置这句话
/* TIM9 enable counter */
TIM_Cmd(TIM12, ENABLE);
}
/*******************************************************************************
* Function Name : EXTI_Configuration
* Description : None
* Input : None
* Output : None
* Return : None
*******************************************************************************/
void EXTI_Configuration(void)
{
// EXTI_InitTypeDef EXTI_InitStructure;
// GPIO_InitTypeDef GPIO_InitStructure;
//
// GPIO_InitStructure.GPIO_Pin = GPIO_Pin_8;
// GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN; //输入操作模式
// GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;
// GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz; //速度
// GPIO_Init(GPIOB, &GPIO_InitStructure);
//
// GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9;
// GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN; //输入操作模式
// GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;
// GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz; //速度
// GPIO_Init(GPIOB, &GPIO_InitStructure);
//
// SYSCFG_EXTILineConfig(EXTI_PortSourceGPIOB, EXTI_PinSource8); //选择gpioE2口作为外部中断使用
// EXTI_InitStructure.EXTI_Line = EXTI_Line8; //使能外部中断线2
// EXTI_InitStructure.EXTI_Mode = EXTI_Mode_Interrupt; //外部中断
// EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_-Falling; //配置为上升沿触发 //下降沿是EXTI_Trigger_Falling
// EXTI_InitStructure.EXTI_LineCmd = ENABLE; //双边沿 EXTI_Trigger_Rising_Falling
// EXTI_Init(&EXTI_InitStructure);
//
// SYSCFG_EXTILineConfig(EXTI_PortSourceGPIOB, EXTI_PinSource9); //选择gpioE2口作为外部中断使用
// EXTI_InitStructure.EXTI_Line = EXTI_Line9; //使能外部中断线2
// EXTI_InitStructure.EXTI_Mode = EXTI_Mode_Interrupt; //外部中断
// EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Falling; //配置为上升沿触发 //下降沿是EXTI_Trigger_Falling
// EXTI_InitStructure.EXTI_LineCmd = ENABLE; //双边沿 EXTI_Trigger_Rising_Falling
// EXTI_Init(&EXTI_InitStructure);
}
/*******************************************************************************
* Function Name : NVIC_Configuration
* Description : Configures Vector Table base location.
* Input : None
* Output : None
* Return : None
*******************************************************************************/
void NVIC_Configuration(void)
{
NVIC_InitTypeDef NVIC_InitStructure;
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2); //优先级组选择 第0组
/*优先级组的分配只能设置一次 第几组,抢占式优先级就有几位*/
NVIC_InitStructure.NVIC_IRQChannel = USART1_IRQn; //串口中断
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0; //主优先级
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0; //从优先级
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; //使能
NVIC_Init(&NVIC_InitStructure);
// NVIC_InitStructure.NVIC_IRQChannel = EXTI15_10_IRQn; //外部中断 中断线2的中断
// NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 1; //主优先级
// NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0; //从优先级
// NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; //使能
// NVIC_Init(&NVIC_InitStructure);
// NVIC_InitStructure.NVIC_IRQChannel = EXTI9_5_IRQn; //外部中断 中断线2的中断
// NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 1; //主优先级
// NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0; //从优先级
// NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; //使能
// NVIC_Init(&NVIC_InitStructure);
// NVIC_InitStructure.NVIC_IRQChannel = EXTI2_IRQn; //外部中断 中断线2的中断
// NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 1; //主优先级
// NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0; //从优先级
// NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; //使能
// NVIC_Init(&NVIC_InitStructure);
//
// NVIC_InitStructure.NVIC_IRQChannel = TIM4_IRQn; //定时器2的中断
// NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 2; //主优先级
// NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0; //从优先级
// NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; //使能
// NVIC_Init(&NVIC_InitStructure);
}
/*******************************************************************************
* Function Name : CAN1_Configuration
* Description : None
* Input : None
* Output : None
* Return : None
*******************************************************************************/
void CAN1_Configuration(void)
{
}
| [
"[email protected]"
] | |
c9b1df0798527f0818087b04118decf84a0bd57e | b4a804078c2db0e24d7b9daae54019a7277df979 | /GLSample/WinMain.c | 32e4ede4f1827851039973bf3d14b8bece492276 | [] | no_license | esfand/codeproject | 7597de9e62d0ee4508380257e7b572997be1bb27 | 30d6e813ac0de3dd1f6afa7e3386e89deea7c6a3 | refs/heads/master | 2020-04-08T18:13:26.125909 | 2009-02-28T19:43:49 | 2009-02-28T19:43:49 | 138,099 | 5 | 2 | null | null | null | null | WINDOWS-1252 | C | false | false | 25,180 | c | #include "WinMain.h" // standard application include
#include "Util\Misc.h" // miscellaneous routines
#include "Draw\DrawMain.h" // drawing routines
///////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////// MAIN APPLICATION LOGIC //////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////
/*/
/ / -----------------------------------------------------------------------
/ /
/ / Author: Jeremy Lee Falcon
/ / Copyright: ©2002-2006 Jeremy Falcon. All Rights Reserved.
/ / Platforms: Windows 95/98/ME/NT4/2000/XP/2003/Vista
/ / Program: GLSAMPLE.EXE (OpenGL Sample)
/ / Purpose: Sample OpenGL project.
/ /
/ / Description:
/ / [Common Declarations]
/ / This software is not subject to any export provision of
/ / the United States Department of Commerce, and may be
/ / exported to any country or planet.
/ /
/ / [License]
/ / Permission is granted to anyone to use this software for any
/ / purpose on any computer system, and to alter it and
/ / redistribute it freely, subject to the following
/ / restrictions:
/ /
/ / 1. The author is not responsible for the consequences of
/ / use of this software, no matter how awful, even if they
/ / arise from flaws in it.
/ /
/ / 2. The origin of this software must not be misrepresented,
/ / either by explicit claim or by omission. Since few users
/ / ever read sources, credits must appear in the documentation
/ / or about box.
/ /
/ / 3. Altered versions must be plainly marked as such, and
/ / must not be misrepresented as being the original software.
/ /
/ / 4. This notice may not be removed or altered.
/ /
/ / Disclaimer:
/ / THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
/ / ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED
/ / TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
/ / PARTICULAR PURPOSE.
/ /
/ / Notes:
/ / If you have any questions regarding the above clause, please
/ / direct them to [email protected]
/ / -----------------------------------------------------------------------
/*/
// local variables
static bool bGoFullscreen = false;
static unsigned int nRenderThreadID = 0;
static HANDLE hRenderThread = NULL;
// local prototypes
static LRESULT CALLBACK WndProc (HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
static bool GoFullscreen (HWND hWnd, unsigned int nWidth, unsigned int nHeight, BYTE nBits, BYTE nRefresh);
static void GoWindowed (void);
static bool ProcStartOptions (PRENDERARGS pArgs, PRECT pWndRect, HANDLE *pMutex);
///////////////////////////////////////////////////////////////////////////////////////////////////
/*/
/ / int WINAPI
/ / WinMain (HINSTANCE, HINSTANCE, LPSTR, int)
/ /
/ / PURPOSE:
/ / Entry point for the application.
/ /
/ / COMMENTS:
/ / This function initializes the application and processes the window.
/*/
int WINAPI
WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
HWND hWnd = NULL; // handle to the main window
HDC hDC = NULL; // handle to the window's device context
RECT rcWndPos = {0}; // position to use when creating the main app window
HANDLE hMutex = NULL; // handle to the single instance mutex
MSG msg = {0}; // message struct for the queue
RENDERARGS Args = {0}; // arugements to be passed to the render thread
// process independent startup options, if returns false then exit the app
if(ProcStartOptions(&Args, &rcWndPos, &hMutex))
{
WNDCLASS wc = {0}; // window's class struct
DWORD dwWindowStyle = 0; // style bits to use when creating the main app window
HBRUSH hBrush = NULL; // will contain the background color of the main window
// set the background color to black (this may be changed to whatever is needed)
hBrush = CreateSolidBrush(RGB(0, 0, 0));
// we must specify the attribs for the window's class
wc.style = CS_HREDRAW|CS_VREDRAW|CS_OWNDC; // style bits (CS_OWNDC very important for OGL)
wc.lpfnWndProc = (WNDPROC)WndProc; // window procedure to use
wc.cbClsExtra = 0; // no extra data
wc.cbWndExtra = 0; // no extra data
wc.hInstance = hInstance; // associated instance
wc.hIcon = NULL; // use default icon temporarily
wc.hCursor = LoadCursor(NULL, IDC_ARROW); // use default cursor (Windows owns it, so don't unload)
wc.hbrBackground = hBrush; // background brush (don't destroy, let windows handle it)
wc.lpszClassName = APP_CLASSNAME; // class name
// this will create or not create a menu for the main window (depends on app settings)
wc.lpszMenuName = (APP_ALLOW_MENU) ? MAKEINTRESOURCE(IDR_MAINFRAME) : NULL;
// now, we can register this class
RegisterClass(&wc);
// here we determine the correct style bits to use for the man window (depends on settings)
if(bGoFullscreen)
dwWindowStyle = WS_CLIPSIBLINGS|WS_CLIPCHILDREN|WS_POPUP|WS_CLIPCHILDREN;
else
{
dwWindowStyle = (APP_ALLOW_RESIZE) ? WS_OVERLAPPEDWINDOW|WS_CLIPCHILDREN :
WS_OVERLAPPED|WS_CAPTION|WS_SYSMENU|WS_MINIMIZEBOX|WS_CLIPCHILDREN;
}
// use our class to try and create a main window
hWnd = CreateWindow(APP_CLASSNAME, // class to use
APP_NAME, // title for window
dwWindowStyle, // style bits
rcWndPos.left, rcWndPos.top, // position (x, y)
rcWndPos.right, rcWndPos.bottom, // width/height
NULL, // no parent
NULL, // no menu
hInstance, // associated instance
NULL); // no extra data
if(hWnd == NULL)
{
// the window wasn't created, let the user know and leave
MsgBox(NULL, IDS_ERR_CREATEWIN_MAIN, MB_OK|MB_ICONERROR);
}
else
{
PIXELFORMATDESCRIPTOR pfd={0}; // pixel descriptor struct
int nFormat = 0; // index of the closest matching pixel format provided by the system
HICON hIcon = NULL; // handle to the main window's large icon
HICON hIconSmall = NULL; // handle to the main window's small icon
// if we are going fullscreen, then do so here
if(bGoFullscreen)
{
// attempt to enter fullscreen mode
if(!GoFullscreen(hWnd, rcWndPos.right, rcWndPos.bottom, Args.nBPP, Args.nRefresh))
{
MsgBox(NULL, IDS_ERR_DISPLAYMODE, MB_OK|MB_ICONERROR);
return false;
}
}
else
{
// center the window on the screen (if windowed) and no registry data exists for the pos
if(!Args.bZoomed && ((rcWndPos.left == 0)
&& (rcWndPos.top == 0))) MoveWnd(hWnd, MV_CENTER|MV_MIDDLE, NULL);
}
// load the icons we wish to use for the main window
hIcon = (HICON)LoadImage(hInstance, MAKEINTRESOURCE(IDR_MAINFRAME),
IMAGE_ICON, GetSystemMetrics(SM_CXICON), GetSystemMetrics(SM_CYICON), LR_DEFAULTCOLOR);
hIconSmall = (HICON)LoadImage(hInstance, MAKEINTRESOURCE(IDR_MAINFRAME),
IMAGE_ICON, GetSystemMetrics(SM_CXSMICON), GetSystemMetrics(SM_CYSMICON), LR_DEFAULTCOLOR);
/*/
/ / Use our custom icons for the window instead of the Windows'
/ / default icons on the titlebar and when using Alt+Tab key
/*/
SendMessage(hWnd, WM_SETICON, (WPARAM)ICON_BIG, (LPARAM)hIcon);
SendMessage(hWnd, WM_SETICON, (WPARAM)ICON_SMALL, (LPARAM)hIconSmall);
/*/
/ / Now we must set-up the display settings and the render context
/ / to use with the GL. We then enter the traditional message loop
/ / for the window. Afterwards, we need to perform some clean-up.
/*/
// get the window's device context
hDC = GetDC(hWnd);
// set the pixel format for the DC
pfd.nSize = sizeof(pfd);
pfd.nVersion = 1;
pfd.dwFlags = PFD_DRAW_TO_WINDOW|PFD_SUPPORT_OPENGL|PFD_DOUBLEBUFFER;
pfd.iPixelType = PFD_TYPE_RGBA;
pfd.cColorBits = Args.nBPP; // BPP is ignored for windowed mode
pfd.cDepthBits = 16; // 16-bit z-buffer
pfd.iLayerType = PFD_MAIN_PLANE;
// attempt to get a pixel format we'll use for the DC via the RC
nFormat = ChoosePixelFormat(hDC, &pfd);
// if we can't find a format to use, let the user know and split
if(nFormat == 0)
{
MsgBox(hWnd, IDS_ERR_PIXFORMAT, MB_OK|MB_ICONERROR);
}
else
{
DWORD dwCode = 0;
// set the dc to the format we want
SetPixelFormat(hDC, nFormat, &pfd);
// set params to send that haven't been set yet
Args.hWnd = hWnd;
Args.hDC = hDC;
// initialize the scene in a separate thread (do not use CreateThread()
// to avoid leaks caused by the CRT when trying to use standard CRT libs)
hRenderThread = (HANDLE)_beginthreadex(NULL, 0, InitScene, &Args, 0, &nRenderThreadID);
/*/
/ / NOTE: If you do not use a separate thread for rendering, it is imparative
/ / that PeekMessage() is used rather than GetMessage(). But, it is just the
/ / opposite if you do as it will save a bit of processing on this thread.
/*/
// start the endless loop (loop used to process messages for the main window)
// if we want to know when WM_QUIT was sent, the second param must be NULL
while(GetMessage(&msg, NULL, 0, 0) != 0)
{
// send the message off to the appropriate window procedure, as a security
// precaution only do so if it belongs to the the main window in question
if(msg.hwnd == hWnd)
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
// destroy the render thread
if(hRenderThread != NULL) CloseHandle(hRenderThread);
}
// clean-up (windows specific items)
ReleaseDC(hWnd, hDC);
if(bGoFullscreen) GoWindowed();
if(hMutex != NULL) CloseHandle(hMutex);
if(hIcon != NULL) DestroyIcon(hIcon);
if(hIconSmall != NULL) DestroyIcon(hIconSmall);
}
// clean-up (windows specific items)
if(hBrush != NULL) DeleteObject(hBrush);
}
// terminate the application
return msg.wParam;
}
///////////////////////////////////////////////////////////////////////////////////////////////////
/*/
/ / LRESULT CALLBACK
/ / WndProc (HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
/ /
/ / hWnd = handle to the window the message belongs to
/ / uMsg = message to process
/ / wParam = word sized param who's value depends on the message
/ / lParam = long sized param who's value depends on the message
/ /
/ / PURPOSE:
/ / Window procedure to handle messages for the main window.
/*/
static LRESULT CALLBACK
WndProc (HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
LRESULT lReturn = false;
switch(uMsg)
{
case UWM_SHOW:
// the render thread will send this message when its inits are done
// wParam will contain true if we are to maximize the window
if((bool)wParam == true)
{
// if the user left the window maxed on close, then restore the state
// note: must be done this way b/c when the window style is set to
// overlapped window, Windows ignores the maxed style bit
ShowWindow(hWnd, SW_MAXIMIZE);
}
else
ShowWindow(hWnd, SW_SHOW);
// give a slightly higher priority and set keyboard focus
SetForegroundWindow(hWnd);
SetFocus(hWnd);
// let the caller know this message was processed
lReturn = true;
break;
case WM_CLOSE:
// before the main window is destroyed, save it's position (and width/height) if in windowed mode
// NOTE: do not perform this operation if windows is closed in a maxed or mined state
if(!bGoFullscreen)
{
if(!IsIconic(hWnd))
{
RECT rcWndPos = {0}; // contains the pos and size of the window
GetWindowRect(hWnd, &rcWndPos);
// save width/height data if allowed to resize
if(APP_ALLOW_RESIZE)
{
bool bZoomed = IsZoomed(hWnd);
// save position data (even if maximized as it will tell us which monitor to maximize on)
SetUserValue(NULL, _T("Left"), REG_DWORD, &rcWndPos.left, sizeof(LONG));
SetUserValue(NULL, _T("Top"), REG_DWORD, &rcWndPos.top, sizeof(LONG));
// only save size data if the app is not maximized
if(!bZoomed)
{
long lWidth = 0, lHeight = 0;
lWidth = rcWndPos.right - rcWndPos.left;
lHeight = rcWndPos.bottom - rcWndPos.top;
SetUserValue(NULL, _T("Width"), REG_DWORD, &lWidth, sizeof(lWidth));
SetUserValue(NULL, _T("Height"), REG_DWORD, &lHeight, sizeof(lHeight));
}
// if we are in windowed mode, save the maxed state to restore later
SetUserValue(NULL, _T("Zoom"), REG_DWORD, &bZoomed, sizeof(bZoomed));
}
else
{
// save position data
SetUserValue(NULL, _T("Left"), REG_DWORD, &rcWndPos.left, sizeof(LONG));
SetUserValue(NULL, _T("Top"), REG_DWORD, &rcWndPos.top, sizeof(LONG));
}
}
}
// we need to shutdown the render thread, so we signal it to stop
// to play nice, let it finish before proceeding (up to 5 seconds)
if((hRenderThread) != NULL && (nRenderThreadID > 0))
{
PostThreadMessage(nRenderThreadID, UWM_STOP, 0, 0);
WaitForSingleObject(hRenderThread, 5000);
}
// destroy this window and thus the app as requsted
DestroyWindow(hWnd);
break;
case WM_DESTROY:
// send WM_QUIT and close main running thread
PostQuitMessage(true);
break;
case WM_ENTERMENULOOP:
// NOTE: always leave this whether or not the app has a menu! (remember the sys menu)
// suspend the render thread if the user is navigating menus (if not minimized)
if(!IsIconic(hWnd)) PostThreadMessage(nRenderThreadID, UWM_PAUSE, true, 0);
break;
case WM_EXITMENULOOP:
// NOTE: always leave this whether or not the app has a menu! (remember the sys menu)
// start the render thread back up if the user leaves the menu (if not minimized)
if(!IsIconic(hWnd)) PostThreadMessage(nRenderThreadID, UWM_PAUSE, false, 0);
break;
case WM_GETMINMAXINFO:
// must specify a minimun for both aspects before we care
if(APP_ALLOW_RESIZE && (APP_MIN_HEIGHT > 0) && (APP_MIN_WIDTH > 0))
{
MINMAXINFO *pInfo = (MINMAXINFO *)lParam;
// we use the message to enforce a minimum width and height of the window (if desired)
pInfo->ptMinTrackSize.x = APP_MIN_HEIGHT;
pInfo->ptMinTrackSize.y = APP_MIN_WIDTH;
}
break;
case WM_KEYDOWN:
switch(wParam)
{
case VK_ESCAPE:
// if we are in fullscreen mode only
if(bGoFullscreen)
{
HMENU hMenu = NULL;
bool bHidden = false;
// get the handle of the menubar (if present)
hMenu = GetMenu(hWnd);
// to determine what gets done, we use a boolean
// stored in the window's userdata buffer
bHidden = (bool)GetWindowLongPtr(hWnd, GWL_USERDATA);
// the ESC key can do one of two things in fullscreen mode, if there
// is a menu, it will show and hide it otherwise it will exit the app
// if the menu is hidden then we do not process this (we toggle it)
if((hMenu == NULL) && !bHidden)
{
// no menu so close the application down
SendMessage(hWnd, WM_CLOSE, 0, 0);
}
else
{
if(bHidden)
{
// recreate the menubar to toggle it on and show cursor
SetMenu(hWnd, LoadMenu(GetWindowInstance(hWnd), MAKEINTRESOURCE(IDR_MAINFRAME)));
ShowCursor(true);
// set the userdata to false to indicate we toggled the menu
SetWindowLongPtr(hWnd, GWL_USERDATA, false);
}
else
{
// we have a menubar that's shown, so toggle it off and hide cursor
SetMenu(hWnd, NULL);
ShowCursor(false);
// set the userdata to true to indicate we toggled the menu
SetWindowLongPtr(hWnd, GWL_USERDATA, true);
}
}
}
break;
}
break;
case WM_SIZE:
switch(wParam)
{
case SIZE_MINIMIZED:
// play nice and don't hog the computer if minimized
PostThreadMessage(nRenderThreadID, UWM_PAUSE, true, 0);
break;
case SIZE_RESTORED:
// we need to resize the viewport for OGL, but it must be done in the
// context of the render thread, so set the signal to be picked up
PostThreadMessage(nRenderThreadID, UWM_RESIZE, 0, 0);
// back in action, so let the threads continue
PostThreadMessage(nRenderThreadID, UWM_PAUSE, false, 0);
break;
}
break;
default:
lReturn = DefWindowProc(hWnd, uMsg, wParam, lParam);
}
return lReturn;
}
///////////////////////////////////////////////////////////////////////////////////////////////////
/*/
/ / bool
/ / GoFullscreen (HWND hWnd, unsigned int nWidth, unsigned int nHeight, BYTE nBits, BYTE nRefresh)
/ /
/ / hWnd = handle to the associated window to work with
/ / nWidth = width to set the display's resolution to
/ / nHeight = height to set the display's resolution to
/ / nBits = bits per pixel to use
/ / nRefresh = vertical refresh rate to use
/ /
/ / PURPOSE:
/ / Sets the display to fullscreen mode.
/*/
static bool
GoFullscreen (HWND hWnd, unsigned int nWidth, unsigned int nHeight, BYTE nBits, BYTE nRefresh)
{
DEVMODE dm = {0}; // device mode structure
dm.dmSize = sizeof(DEVMODE);
dm.dmPelsWidth = nWidth; // screen width
dm.dmPelsHeight = nHeight; // screen height
dm.dmBitsPerPel = nBits; // display bits per pixel (BPP)
dm.dmFields = DM_BITSPERPEL|DM_PELSWIDTH|DM_PELSHEIGHT; // flags
// as a safey precaution, double check to make sure the refresh rate is in range
if((nRefresh >= APP_MIN_REFRESH) && (nRefresh <= APP_MAX_REFRESH))
dm.dmDisplayFrequency = nRefresh;
// attempt to move to fullscreen
if(ChangeDisplaySettings(&dm, CDS_FULLSCREEN) != DISP_CHANGE_SUCCESSFUL)
return false;
else
{
// hide the cursor (if in fullscreen with no menu)
if(GetMenu(hWnd) == NULL) ShowCursor(false);
return true;
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////
/*/
/ / void
/ / GoWindowed (void)
/ /
/ / PURPOSE:
/ / Sets the display to windowed mode.
/*/
static void
GoWindowed (void)
{
ChangeDisplaySettings(NULL, 0); // switch back to the desktop
ShowCursor(true); // show the cursor again
}
///////////////////////////////////////////////////////////////////////////////////////////////////
/*/
/ / void
/ / ProcessOptions (PRENDERARGS pArgs, PRECT pWndRect, HANDLE *pMutex)
/ /
/ / pArgs = pointer to the argument structure that will eventually get sent to the render thread.
/ / pWndRect = pointer to a rect to receive the coordinates for the main window to create with
/ / pMutex = pointer to a mutex handle used to determine if this app will be a single instance or not
/ /
/ / PURPOSE:
/ / Processes the app defined options and command line options. Returns
/ / false if the app needs to be shutdown or true otherwise.
/*/
static bool
ProcStartOptions (PRENDERARGS pArgs, PRECT pWndRect, HANDLE *pMutex)
{
bool bReturn = true;
TCHAR szBuff[MAX_LOADSTRING] = {0};
// first and foremost, make sure the host os meets our requirements
// depending on config, check for version and nt only or both nt and 9x (no check for only 9x)
if(!WIN_MIN_VERSION(APP_MIN_WINVER_MAJOR, APP_MIN_WINVER_MINOR) || (APP_WINVER_NTONLY && !IS_WINNT))
{
MsgBox(NULL, IDS_ERR_WINVER, MB_OK|MB_ICONERROR);
bReturn = false;
}
else
{
if(APP_SINGLE_INSTANCE && (pMutex != NULL))
{
*pMutex = CreateMutex(NULL, true, APP_CLASSNAME);
// limit this app to a single instance only (make sure classname is unique)
// NOTE: using a mutex is MUCH safer than using FindWindow() alone, if the
// exe gets executed back-to-back - as in a script - mutexes still work
if(GetLastError() == ERROR_ALREADY_EXISTS)
{
HWND hPrevious = NULL;
// set focus to the other main window (if possible, may not be created yet) then exit
// if the class name is unique we don't worry about searching against the title
if((hPrevious = FindWindow(APP_CLASSNAME, NULL)) != NULL)
ShowWindow(hPrevious, SW_SHOWNORMAL);
bReturn = false;
}
}
// don't bother processing the rest if the app is just going to be shutdown
if(bReturn && (pArgs != NULL) && (pWndRect != NULL))
{
DWORD dwTemp = 0; // used to pull dword values from the registry
/*/
/ / Here, we need to determine if this app allows fullscreen mode. If so, do we default
/ / to it or not? If not, then process nothing and stay windowed. If it is allowed, then
/ / we need to specify the fullscreen cmd arg and set it's value to yes or no (default yes).
/*/
if(APP_ALLOW_FULLSCREEN)
{
// read the cmd ling arg to see what we should do about fullscreen
if(GetCmdLineValue(_T("fullscreen"), szBuff, REAL_SIZE(szBuff)))
{
// any value other than "no" (including no value) is considered a yes
if(!MATCH(szBuff, _T("no"))) bGoFullscreen = true;
}
else
{
// command line arg not found, but we need to check if we default to fullscreen
if(APP_DEF_FULLSCREEN) bGoFullscreen = true;
}
// set the param that will eventually be sent to the render thread
pArgs->bFullscreen = bGoFullscreen;
}
// get the bits per pixel data (if any) from the registry, can only be 8, 16, 24, or 32
dwTemp = 0;
if(!GetUserValue(NULL, _T("BPP"), REG_DWORD, &dwTemp, sizeof(dwTemp)))
pArgs->nBPP = APP_DEF_BPP;
else
{
// to be valid, it must be a mulitple of 8 in the range of 8-32, otherwise use the default
if(dwTemp < 8 || dwTemp > 32) dwTemp = APP_DEF_BPP;
if((dwTemp % 8) != 0) dwTemp = APP_DEF_BPP;
// finally set the BPP value
pArgs->nBPP = (BYTE)dwTemp;
}
// get the vertical refresh rate data (if any) from the registry, must be between min and max
dwTemp = 0;
if(!GetUserValue(NULL, _T("Refresh"), REG_DWORD, &dwTemp, sizeof(dwTemp)))
pArgs->nRefresh = APP_MIN_REFRESH;
else
{
// to be valid, it must be between the min and max, otherwise use the default
if(dwTemp > APP_MAX_REFRESH)
pArgs->nRefresh = APP_MAX_REFRESH;
else if(dwTemp < APP_MIN_REFRESH)
pArgs->nRefresh = APP_MIN_REFRESH;
else
pArgs->nRefresh = (BYTE)dwTemp;
}
/*/
/ / Here, we need to determine if we need to set the vertical on or off. It's important to
/ / note, on nVidia cards, this can be overriden so the app is not able to adjust this.
/ / If it is not allowed, the whatever setting/default set by the video card will take effect.
/*/
if(APP_ALLOW_VSYNC)
{
// assume vsync is false if no setting is found
dwTemp = 0;
if(!GetUserValue(NULL, _T("VSync"), REG_DWORD, &dwTemp, sizeof(dwTemp)))
// if no option is set, then default
pArgs->Status = VSync_Default;
else
// ensure we are working with proper boolean data
pArgs->Status = (dwTemp == 0) ? VSync_Off : VSync_On;
}
else
// not allowed, so default to leaving vsync alone
pArgs->Status = VSync_Default;
/*/
/ / At this point we need to see if the registry contains data regarding the main window pos.
/ / Of course, we only care about this if not in fullscreen mode, but check now to reduce flicker.
/*/
// independently test left/top (if not in registry then we center the window later on)
// if we are in fullscreen mode, always leave these set to zero
if(!bGoFullscreen)
{
GetUserValue(NULL, _T("Left"), REG_DWORD, &pWndRect->left, sizeof(LONG));
GetUserValue(NULL, _T("Top"), REG_DWORD, &pWndRect->top, sizeof(LONG));
}
// just in case the data was corrupted, perform a bit of checking (no negative values are allowed)
pWndRect->left = (unsigned long)pWndRect->left;
pWndRect->top = (unsigned long)pWndRect->top;
/*/
/ / IMPORTANT: if we do not allow the user to resize then never, ever use the values from the registry as this
/ / will create an exploit, so in this case we always use the defaults and allow the programmer to adjust them
/ / as needed, also if the app will only run in fullscreen mode it should always turn APP_ALLOW_RESIZE off
/*/
if(APP_ALLOW_RESIZE)
{
// if this data doesn't exist or is bogus, we just revert back to the default width/height
GetUserValue(NULL, _T("Width"), REG_DWORD, &pWndRect->right, sizeof(LONG));
GetUserValue(NULL, _T("Height"), REG_DWORD, &pWndRect->bottom, sizeof(LONG));
pWndRect->right = (pWndRect->right <= 0) ? APP_DEF_WIDTH : pWndRect->right;
pWndRect->bottom = (pWndRect->bottom <= 0) ? APP_DEF_HEIGHT : pWndRect->bottom;
if(!bGoFullscreen)
{
// if we are in windowed mode, get the maximized state so we can restore it if needed
dwTemp = 0;
if(!GetUserValue(NULL, _T("Zoom"), REG_DWORD, &dwTemp, sizeof(dwTemp)))
pArgs->bZoomed = false;
else
// ensure we are working with proper boolean data
pArgs->bZoomed = (dwTemp == 0) ? false : true;
}
}
else
{
pWndRect->right = APP_DEF_WIDTH;
pWndRect->bottom = APP_DEF_HEIGHT;
}
}
}
return bReturn;
}
///////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////// | [
"[email protected]"
] | |
9836c92cf6c6f349304b4b7570283ef233cb1882 | 3fdaced9025cb2e3db75ca191d9cfe352180d8d9 | /Libraries/emWin/Sample/GUI_X/GUI_VNC_X_StartServer.c | 92826edf377920007bd634fc818f53b905f3ec72 | [] | no_license | CloudStudio2017/HeatController | bb957dc3a2c96ae1d1ad720b51ba38d91f9f99bb | 44742acd752b2cd81e49b3e3669bfde2d836f2bc | refs/heads/master | 2021-09-24T12:04:11.298105 | 2018-10-09T17:46:20 | 2018-10-09T17:46:20 | 93,427,353 | 4 | 3 | null | 2018-10-09T17:46:21 | 2017-06-05T17:01:34 | C | UTF-8 | C | false | false | 7,749 | c | /*********************************************************************
* SEGGER Microcontroller GmbH & Co. KG *
* Solutions for real time microcontroller applications *
**********************************************************************
* *
* (c) 1996 - 2015 SEGGER Microcontroller GmbH & Co. KG *
* *
* Internet: www.segger.com Support: [email protected] *
* *
**********************************************************************
** emWin V5.32 - Graphical user interface for embedded applications **
All Intellectual Property rights in the Software belongs to SEGGER.
emWin is protected by international copyright laws. Knowledge of the
source code may not be used to write a similar product. This file may
only be used in accordance with the following terms:
The software has been licensed to ARM LIMITED whose registered office
is situated at 110 Fulbourn Road, Cambridge CB1 9NJ, England solely
for the purposes of creating libraries for ARM7, ARM9, Cortex-M
series, and Cortex-R4 processor-based devices, sublicensed and
distributed as part of the MDK-ARM Professional under the terms and
conditions of the End User License supplied with the MDK-ARM
Professional.
Full source code is available at: www.segger.com
We appreciate your understanding and fairness.
----------------------------------------------------------------------
Licensing information
Licensor: SEGGER Software GmbH
Licensed to: ARM Ltd, 110 Fulbourn Road, CB1 9NJ Cambridge, UK
Licensed SEGGER software: emWin
License number: GUI-00181
License model: LES-SLA-20007, Agreement, effective since October 1st 2011
Licensed product: MDK-ARM Professional
Licensed platform: ARM7/9, Cortex-M/R4
Licensed number of seats: -
----------------------------------------------------------------------
File : GUI_VNC_X_StartServer.c
Purpose : Starts the VNC server via TCP/IP.
This code works with embOS/IP.
However, it can be easily modified to work with
different kernel and IP Stack
---------------------------END-OF-HEADER------------------------------
*/
#include <stdlib.h>
#include "IP.h" // BSD socket interface
#include "RTOS.H" // embOS header
#include "GUI.h"
#include "GUI_VNC.h"
/*********************************************************************
*
* Static data
*
**********************************************************************
*/
static GUI_VNC_CONTEXT _Context;
static struct sockaddr_in _Addr;
//
// embOS Stack area of the server
//
static OS_STACKPTR int _StackVNCServer[1000];
//
// embOS Task-control-block of the server
//
static OS_TASK _VNCServer_TCB;
/*********************************************************************
*
* Static functions
*
**********************************************************************
*/
/*********************************************************************
*
* _Send
*
* Function description
* This function is called indirectly by the server; it's address is passed to the actual
* server code as function pointer. It is needed because the server is independent
* of the TCP/IP stack implementation, so details for the TCP/IP stack can be placed here.
*/
static int _Send(const U8 * buf, int len, void * pConnectionInfo) {
int r;
r = send((long)pConnectionInfo, (const char *)buf, len, 0);
return r;
}
/*********************************************************************
*
* _Recv
*
* Function description
* This function is called indirectly by the server; it's address is passed to the actual
* server code as function pointer. It is needed because the server is independent
* of the TCP/IP stack implementation, so details for the TCP/IP stack can be placed here.
*/
static int _Recv(U8 * buf, int len, void * pConnectionInfo) {
return recv((long)pConnectionInfo, (char *)buf, len, 0);
}
/*********************************************************************
*
* _ListenAtTcpAddr
*
* Starts listening at the given TCP port.
*/
static int _ListenAtTcpAddr(U16 Port) {
int sock;
struct sockaddr_in addr;
sock = socket(AF_INET, SOCK_STREAM, 0);
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(Port);
addr.sin_addr.s_addr = INADDR_ANY;
bind(sock, (struct sockaddr *)&addr, sizeof(addr));
listen(sock, 1);
return sock;
}
/*********************************************************************
*
* _ServerTask
*
* Function description
* This routine is the actual server task.
* It executes some one-time init code, then runs in an ednless loop.
* It therefor does not terminate.
* In the endless loop it
* - Waits for a conection from a client
* - Runs the server code
* - Closes the connection
*/
static void _ServerTask(void) {
int s, Sock, AddrLen;
U16 Port;
//
// Prepare socket (one time setup)
//
Port = 5900 + _Context.ServerIndex; // Default port for VNC is is 590x, where x is the 0-based layer index
//
// Loop until we get a socket into listening state
//
do {
s = _ListenAtTcpAddr(Port);
if (s != -1) {
break;
}
OS_Delay(100); // Try again
} while (1);
//
// Loop once per client and create a thread for the actual server
//
while (1) {
//
// Wait for an incoming connection
//
AddrLen = sizeof(_Addr);
if ((Sock = accept(s, (struct sockaddr*)&_Addr, &AddrLen)) == SOCKET_ERROR) {
continue; // Error
}
//
// Run the actual server
//
GUI_VNC_Process(&_Context, _Send, _Recv, (void *)Sock);
//
// Close the connection
//
closesocket(Sock);
memset(&_Addr, 0, sizeof(struct sockaddr_in));
}
}
/*********************************************************************
*
* Public code
*
**********************************************************************
*/
/*********************************************************************
*
* GUI_VNC_X_StartServer
*
* Function description
* To start the server, the following steps are executed
* - Make sure the TCP-IP stack is up and running
* - Init the server context and attach it to the layer
* - Start the thread (task) which runs the VNC server
* Notes:
* (1) The first part of the code initializes the TCP/IP stack. In a typical
* application, this is not required, since the stack should have already been
* initialized some other place.
* This could be done in a different module. (TCPIP_AssertInit() ?)
*/
int GUI_VNC_X_StartServer(int LayerIndex, int ServerIndex) {
//
// Init VNC context and attach to layer (so context is updated if the display-layer-contents change
//
GUI_VNC_AttachToLayer(&_Context, LayerIndex);
_Context.ServerIndex = ServerIndex;
//
// Create task for VNC Server
//
OS_CREATETASK(&_VNCServer_TCB, "VNC Server", _ServerTask, 230, _StackVNCServer);
//
// O.k., server has been started
//
return 0;
}
/*********************************************************************
*
* GUI_VNC_X_getpeername
*
* Function description
* Retrieves the IP addr. of the currently connected VNC client.
*
* Return values
* IP addr. if VNC client connected
* 0 if no client connected
*/
void GUI_VNC_X_getpeername(U32 * Addr) {
*Addr = _Addr.sin_addr.s_addr;
}
/*************************** End of file ****************************/
| [
"[email protected]"
] | |
07733591d3f686c22177d19a1d20375ff1ace638 | e256fb3b0db865612ef866c015e9931b5a0f8737 | /Lab4/troys002_lab4_part5.c | 2d13450aeaabca3942f5ca30a01d9aa4b8de5f03 | [] | no_license | tcroyston/1_2_0 | 646a9318bdeb2b1b400909b1717a16e5ad868bb1 | 4276a5e48c5a34296139dce8e50f78c6476d6373 | refs/heads/main | 2023-07-17T20:13:24.195871 | 2021-08-25T21:39:40 | 2021-08-25T21:39:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C | false | false | 2,303 | c | /* Author: troys002
* Partner(s) Name: (none)
* Lab Section: 22
* Assignment: Lab #4 Exercise #5
* Exercise Description: [optional - include for your own benefit]
*
* I acknowledge all content contained herein, excluding template or example
* code, is my own original work.
*/
#include <avr/io.h>
#ifdef _SIMULATE_
#include "simAVRHeader.h"
enum States{start, init, lock, pound, check, standby, pause, unlock}state;
#endif
unsigned char array[3] = {0x01, 0x02, 0x01};
unsigned char i = 0;
void tick(){
switch(state){//transitions
case start:
state = init;
break;
case init:
if(PINA == 0x80){
state = lock;
}
else if(PINA == 0x04){
state = pound;
}
else{
state = init;
}
break;
case lock:
if(PINA == 0x00){
state = init;
}
else{
state = lock;
}
break;
case pound:
if(PINA == 0x00){
state = check;
}
else{
state = pound;
}
break;
case check:
if(PINA == array[i] ){
state = standby;
}
else if(i == 0x04){
state = unlock;
}
else if(PINA == 0x08){
state = lock;
}
else if(PINA = 0x00){
state = check;
}
else if(PINA != array[i]){
PORTB = 0x01;
state = pause;
}
break;
case standby:
if(PINA = 0x00){
++i;
state = check;
}
else{
state = pause;
}
break;
case pause:
if(PINA = 0x00){
state = check;
}
else{
state = init;
}
case unlock:
state = init;
break;
default:
break;
}
switch(state){//actions
default:
break;
case start:
PORTB = 0x00;
break;
case init:
i = 0;
PORTC = 0x01;
break;
case standby:
PORTC = 0x04;
PORTD = i;
case lock:
PORTB = 0x00;
break;
case unlock:
if(PORTB == 0x01){
PORTB = 0x00;
}
else{
PORTB = 0x01;
}
break;
case pound:
PORTC = 0x02;
PORTD = i;
break;
case check:
PORTC = 0x03;
PORTD = i;
break;
case pause:
break;
}
}
int main(void) {
/* Insert DDR and PORT initializations */
DDRA = 0x00; PORTA = 0xFF;
DDRB = 0xFF; PORTB = 0x00;
DDRD = 0xFF; PORTD = 0x00;
DDRC = 0xFF; PORTC = 0x00;
/* Insert your solution below */
state = start;
while (1) {
tick();
}
return 1;
}
| [
"[email protected]"
] | |
bcd962e43de879437921ee70b4c0cf901bee42b6 | 5ab6f15177139ff3f0964b38a6366ee5d69101a9 | /message.c | 4c4ce10e2d79db18f4d87d4193086463ee51e1f3 | [] | no_license | MiguelFale/DistrOnMemKVStore | d11bb687738856200b3857b6e593e91804cbb0ab | 64ba0604b5dd951955ea5bcbedf981f2233b4543 | refs/heads/master | 2021-10-08T18:55:53.503831 | 2018-12-16T11:58:20 | 2018-12-16T11:58:20 | 115,936,120 | 1 | 0 | null | null | null | null | UTF-8 | C | false | false | 8,220 | c | #include <netinet/in.h>
#include <stdlib.h>
#include <string.h>
#include "message-private.h"
#include <stdio.h>
int message_to_buffer(struct message_t *msg, char **msg_buf) {
int size = -1, offset = 0;
short auxs;
long long auxl;
int auxi;
int str;
//esta funcao vai executar de acordo com o c_type da mensagem
switch (msg->c_type) {
case CT_ENTRY:
//somar tamanhos para:
size = sizeof(short) + sizeof(short) + //opcode e c_type
sizeof(long long) + sizeof(int) + //timestamp e tamanho da key
strlen(msg->content.entry->key) + //key
sizeof(int) + //tamanho do data
msg->content.entry->value->datasize; //data
//reservar memoria para o buffer
*msg_buf = (char *) malloc(size);
//memcpy coloca os dados no buffer
//opcode
auxs = htons(msg->opcode);
memcpy(*msg_buf + offset, &auxs, sizeof(short));
offset += sizeof(short);
//c_type
auxs = htons(msg->c_type);
memcpy(*msg_buf + offset, &auxs, sizeof(short));
offset += sizeof(short);
//timestamp
auxl = swap_bytes_64(msg->content.entry->timestamp);
memcpy(*msg_buf + offset, &auxl, sizeof(long long));
offset += sizeof(long long);
//tamanho da key
auxi = htonl(strlen(msg->content.entry->key));
memcpy(*msg_buf + offset, &auxi, sizeof(int));
offset += sizeof(int);
//key
memcpy(*msg_buf + offset, msg->content.entry->key,
strlen(msg->content.entry->key));
offset += strlen(msg->content.entry->key);
//tamanho do data
auxi = htonl(msg->content.entry->value->datasize);
memcpy(*msg_buf + offset, &auxi, sizeof(int));
offset += sizeof(int);
//data
memcpy(*msg_buf + offset, msg->content.entry->value->data,
msg->content.entry->value->datasize);
break;
case CT_KEY:
//somar tamanhos para:
size = sizeof(short) + sizeof(short) + //opcode e c_type
sizeof(int) + strlen(msg->content.key); //tamanho da key e key
//reservar memoria para o buffer
*msg_buf = (char *) malloc(size);
//memcpy coloca os dados no buffer
auxs = htons(msg->opcode);
memcpy(*msg_buf + offset, &auxs, sizeof(short));
offset += sizeof(short);
auxs = htons(msg->c_type);
memcpy(*msg_buf + offset, &auxs, sizeof(short));
offset += sizeof(short);
//tamanho da key
auxi = htonl(strlen(msg->content.key));
memcpy(*msg_buf + offset, &auxi, sizeof(int));
offset += sizeof(int);
//key
memcpy(*msg_buf + offset, msg->content.key, strlen(msg->content.key));
break;
case CT_KEYS:
//somar tamanhos para:
size = sizeof(short) + sizeof(short) + //opcode e c_type
sizeof(int); //numero de keys
int i = 0, n = 0, j, soma = 0;
for (; msg->content.keys[i] != NULL; i++) {
n++; //para se saber o numero de keys
soma += strlen(msg->content.keys[i]); //soma dos tamanhos das keys
}
size += soma * sizeof(char) + n * sizeof(int);
//reservar memoria para o buffer
*msg_buf = (char *) malloc(size);
//memcpy coloca os dados no buffer
auxs = htons(msg->opcode);
memcpy(*msg_buf + offset, &auxs, sizeof(short));
offset += sizeof(short);
auxs = htons(msg->c_type);
memcpy(*msg_buf + offset, &auxs, sizeof(short));
offset += sizeof(short);
//numero de keys
auxi = htonl(n);
memcpy(*msg_buf + offset, &auxi, sizeof(int));
offset += sizeof(int);
//pares (tamanho da key, key)
for (j = 0; j < n; j++) {
str = strlen(msg->content.keys[j]);
auxi = htonl(str);
memcpy(*msg_buf + offset, &auxi, sizeof(int));
offset += sizeof(int);
memcpy(*msg_buf + offset, msg->content.keys[j], str);
offset += str;
}
break;
case CT_VALUE:
//somar tamanhos para:
size = sizeof(short) + sizeof(short) + //opcode e c_type
sizeof(int) + msg->content.value->datasize; //datasize e data
//reservar memoria para o buffer
*msg_buf = (char *) malloc(size);
auxs = htons(msg->opcode);
memcpy(*msg_buf + offset, &auxs, sizeof(short));
offset += sizeof(short);
auxs = htons(msg->c_type);
memcpy(*msg_buf + offset, &auxs, sizeof(short));
offset += sizeof(short);
//datasize
auxi = htonl(msg->content.value->datasize);
memcpy(*msg_buf + offset, &auxi, sizeof(int));
offset += sizeof(int);
//data
memcpy(*msg_buf + offset, msg->content.value->data,
msg->content.value->datasize);
break;
case CT_RESULT:
size = sizeof(short) + sizeof(short) + //opcode e c_type
sizeof(int); //resultado
//reservar memoria para o buffer
*msg_buf = (char *) malloc(size);
auxs = htons(msg->opcode);
memcpy(*msg_buf + offset, &auxs, sizeof(short));
offset += sizeof(short);
auxs = htons(msg->c_type);
memcpy(*msg_buf + offset, &auxs, sizeof(short));
offset += sizeof(short);
//resultado
auxi = htonl(msg->content.result);
memcpy(*msg_buf + offset, &auxi, sizeof(int));
break;
}
return size;
}
struct message_t *buffer_to_message(char *msg_buf, int msg_size) {
int offset = 0;
int n, j;
struct message_t *msg = (struct message_t *) malloc(
sizeof(struct message_t));
int size_string;
int sizeCT;
long long templ;
char *temps;
void *tempv;
//passar primeiro com o memcpy e depois converter
memcpy(&msg->opcode, msg_buf + offset, sizeof(short)); //OCPODE
msg->opcode = ntohs(msg->opcode);
offset += sizeof(short);
memcpy(&msg->c_type, msg_buf + offset, sizeof(short)); //C_TYPE
msg->c_type = ntohs(msg->c_type);
offset += sizeof(short);
switch (msg->c_type) {
case CT_ENTRY:
memcpy(&templ, msg_buf + offset, sizeof(long long)); //TIMESTAMP
templ = swap_bytes_64(templ);
offset += sizeof(long long);
memcpy(&size_string, msg_buf + offset, sizeof(int)); //KEYSIZE
size_string = ntohl(size_string);
offset += sizeof(int);
temps = (char *) malloc(sizeof(char) * (size_string + 1));
memcpy(temps, msg_buf + offset, size_string); //KEY
temps[size_string] = '\0';
offset += size_string;
memcpy(&(sizeCT), msg_buf + offset, sizeof(int)); //DATASIZE
sizeCT = ntohl(sizeCT);
offset += sizeof(int);
tempv = malloc(sizeCT); //DATA
msg->content.entry = entry_create(temps,
data_create2(sizeCT, memcpy(tempv, msg_buf + offset, sizeCT)));
msg->content.entry->timestamp = templ;
msg->content.entry->key = temps;
offset += sizeCT;
break;
case CT_KEY:
memcpy(&size_string, msg_buf + offset, sizeof(int)); //KEYSIZE
size_string = ntohl(size_string);
offset += sizeof(int);
msg->content.key = (char *) malloc(sizeof(char) * (size_string + 1));
memcpy(msg->content.key, msg_buf + offset, size_string); //KEY
msg->content.key[size_string] = '\0';
offset += size_string;
break;
case CT_KEYS:
memcpy(&n, msg_buf + offset, sizeof(int)); //NKEYS
n = ntohl(n);
offset += sizeof(int);
msg->content.keys = (char **) malloc((n + 1) * sizeof(char *));
for (j = 0; j < n; j++) {
memcpy(&size_string, msg_buf + offset, sizeof(int)); //KEYSIZE
size_string = ntohl(size_string);
offset += sizeof(int);
msg->content.keys[j] = (char *) malloc(
sizeof(char) * (size_string + 1));
memcpy(msg->content.keys[j], msg_buf + offset, size_string);
msg->content.keys[j][size_string] = '\0'; //KEY
offset += size_string;
}
msg->content.keys[n] = NULL;
break;
case CT_VALUE:
memcpy(&(sizeCT), msg_buf + offset, sizeof(int)); //DATASIZE
sizeCT = ntohl(sizeCT);
offset += sizeof(int);
msg->content.value = data_create(sizeCT);
memcpy(msg->content.value->data, msg_buf + offset,
msg->content.value->datasize); //DATA
offset += sizeCT;
break;
case CT_RESULT:
memcpy(&msg->content.result, msg_buf + offset, sizeof(int)); //RESULT
msg->content.result = ntohl(msg->content.result);
offset += sizeof(int);
break;
default:
//nao fazer a mensagem em caso de buffer invalido
free_message(msg);
msg = NULL;
break;
}
if (offset != msg_size)
return NULL;
return msg;
}
void free_message(struct message_t *message) {
//liberta o respetivo conteudo
switch (message->c_type) {
case CT_ENTRY:
entry_destroy(message->content.entry);
break;
case CT_KEY:
free(message->content.key);
break;
case CT_KEYS:
//esta funcao tem um mecanismo identico ao pretendido
list_free_keys(message->content.keys);
break;
case CT_VALUE:
data_destroy(message->content.value);
break;
}
//por fim apagar a estrutura
free(message);
}
| [
"[email protected]"
] | |
8b643887a46b2b68c7655c89e40e1c92965eb353 | 7d098aa1c5dcda13f5e72a936e2fe97dd19e39a0 | /0x05-pointers_arrays_strings/3-puts.c | bc2a5792eb561335051e82561fac31422c997a17 | [] | no_license | nicollem05/holbertonschool-low_level_programming | f0ab7b587d894b9013bf7ac4dc4150f8bc1dffc3 | 672a043de3d5baac77dae05426a8ecc67bfcf44b | refs/heads/master | 2022-11-10T00:51:36.809081 | 2020-06-24T04:10:46 | 2020-06-24T04:10:46 | 271,315,602 | 0 | 0 | null | null | null | null | UTF-8 | C | false | false | 232 | c | #include "holberton.h"
/**
* _puts -prints a string followed by a line
* @str: this is a pointer
* Return: 0
*/
void _puts(char *str)
{
int a;
for (a = 0; str[a] != '\0'; a++)
{
_putchar(str[a]);
}
_putchar('\n');
}
| [
"[email protected]"
] | |
0990fb2a9ad21b2871666470088b96d591a69a15 | 30b048388add1dcaea3a88a9f975f2cdee66a817 | /C03/ex05/main.c | 7d0299e047faaf0106315603c05e20510256488c | [] | no_license | GITADDed/tzenyatt | db4add5f9bebc280318c57d8609692c5060af673 | 3a3ae5f26f1af2587357c3121ee9325820bb7af8 | refs/heads/master | 2023-04-27T22:22:25.579194 | 2021-05-04T16:08:49 | 2021-05-04T16:08:49 | 282,807,920 | 0 | 0 | null | null | null | null | UTF-8 | C | false | false | 2,661 | c | #include <stdio.h>
#include <string.h>
char *ft_strncat(char *s1, char *s2, unsigned int n);
int main()
{
unsigned int n = 8;
char a[100] = "Hesoyam12";
char b[100] = "hesoyam13355";
printf("EX03\n>>>>>>>>>>>>>>\n\n\nMUST BE : diff = %lu, s1 = %s, s2 = %s, n = %d\n\n", strlcat(a, b, n), a, b, n);
/*char a1[100] = "Hesoyam12";
char b1[100] = "hesoyam1";
printf("WHAT RESULT : diff = %s, s1 = %s, s2 = %s, n = %d\n\n\n\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n\n", ft_strncat(a1 , b1, n), a1, b1, n);
char a3[100] = "Hesoyam12";
char b3[100] = "hesoyam1";
printf("MUST BE : diff = %s, s1 = %s, s2 = %s, n = %d\n\n", strncat(b3 , a3, n), b3, a3, n);
char a9[100] = "Hesoyam12";
char b9[100] = "hesoyam1";
printf("WHAT RESULT : diff = %s, s1 = %s, s2 = %s, n = %d\n\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n\n", ft_strncat(b9 , a9, n), b9, a9, n);
char a4[100] = "Luke, I am your father !";
char b4[100] = "Luke, I am your father !";
printf("MUST BE : diff = %s, s1 = %s, s2 = %s, n = %d\n", strncat(a4 , b4, n), a4, b4, n);
char a5[100] = "Luke, I am your father !";
char b5[100] = "Luke, I am your father !";
printf("WHAT RESULT : diff = %s, s1 = %s, s2 = %s, n = %d\n\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n\n", ft_strncat(a5 , b5, n), a5, b5, n);
n = 17;
char a2[100] = "V means vendetta";
char b2[100] = "V means vendetta!dsadasdadad";
printf("MUST BE : diff = %s, s1 = %s, s2 = %s, n = %d\n", strncat(a2, b2, n), a2, b2, n);
char a6[100] = "V means vendetta";
char b6[100] = "V means vendetta!dsadasdadad";
printf("WHAT RESULT : diff = %s, s1 = %s, s2 = %s, n = %d\n\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n\n", ft_strncat(a6 , b6, n), a6, b6, n);
char a12[100] = "";
char b12[100] = "V means vendetta!dsadasdadad";
printf("MUST BE : diff = %s, s1 = %s, s2 = %s, n = %d\n", strncat(a12, b12, n), a12, b12, n);
char a16[100] = "";
char b16[100] = "V means vendetta!dsadasdadad";
printf("WHAT RESULT : diff = %s, s1 = %s, s2 = %s, n = %d\n\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n\n", ft_strncat(a16 , b16, n), a16, b16, n);
n = 100;
char a7[100] = "V means vendetta";
char b7[100] = "V means vendetta!dsadasdadad";
printf("MUST BE If n > len s1 or s2 : diff = %s, s1 = %s, s2 = %s, n = %d\n", strncat(a7, b7, n), a7, b7, n);
char a8[100] = "V means vendetta";
char b8[100] = "V means vendetta!dsadasdadad";
printf("WHAT RESULT : diff = %s, s1 = %s, s2 = %s, n = %d\n\n##################################################\n##################################################\n\n", ft_strncat(a8 , b8, n), a8, b8, n);*/
}
| [
"[email protected]"
] | |
de65ffa0c51fcf37a128e1fd696bbe2d64f7c162 | c09a93486ce9c7648e9a2e5b93ef25433e1c069a | /c3270.c | 48c634bda414a5ded1c9851284b69aac0a3940a0 | [] | no_license | hharte/c3270 | 1a1d749769ce9ea64bc1a9787c25ab7c02900272 | 3f132b769b205c540d78adb26f36dd0803462c70 | HEAD | 2016-09-05T22:04:27.699953 | 2015-04-27T18:23:52 | 2015-04-27T18:23:52 | 34,683,537 | 3 | 0 | null | null | null | null | UTF-8 | C | false | false | 38,459 | c | /*
* Copyright (c) 1993-2013, Paul Mattes.
* Copyright (c) 1990, Jeff Sparkes.
* Copyright (c) 1989, Georgia Tech Research Corporation (GTRC), Atlanta, GA
* 30332.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the names of Paul Mattes, Jeff Sparkes, GTRC nor the names of
* their contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY PAUL MATTES, JEFF SPARKES AND GTRC "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL PAUL MATTES, JEFF SPARKES OR GTRC BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/*
* c3270.c
* A curses-based 3270 Terminal Emulator
* A Windows console 3270 Terminal Emulator
* Main proceudre.
*/
#include "globals.h"
#if !defined(_WIN32) /*[*/
#include <sys/wait.h>
#endif /*]*/
#include <signal.h>
#include <errno.h>
#include <stdarg.h>
#include "appres.h"
#include "3270ds.h"
#include "resources.h"
#include "actionsc.h"
#include "ansic.h"
#include "charsetc.h"
#include "ctlrc.h"
#include "ftc.h"
#include "gluec.h"
#include "hostc.h"
#include "icmdc.h"
#include "idlec.h"
#include "keymapc.h"
#include "kybdc.h"
#include "macrosc.h"
#include "popupsc.h"
#include "printerc.h"
#include "screenc.h"
#include "statusc.h"
#include "telnetc.h"
#include "togglesc.h"
#include "trace_dsc.h"
#include "utf8c.h"
#include "utilc.h"
#include "xioc.h"
#if defined(HAVE_LIBREADLINE) /*[*/
#include <readline/readline.h>
#if defined(HAVE_READLINE_HISTORY_H) /*[*/
#include <readline/history.h>
#endif /*]*/
#endif /*]*/
#if defined(_WIN32) /*[*/
#include <windows.h>
#include "w3miscc.h"
#include "winversc.h"
#include "windirsc.h"
#include "relinkc.h"
#include <shellapi.h>
#endif /*]*/
#if defined(_WIN32) /*[*/
# define PROGRAM_NAME "wc3270"
#else /*][*/
# define PROGRAM_NAME "c3270"
#endif /*]*/
#if defined(_WIN32) /*[*/
# define DELENV "WC3DEL"
#endif /*]*/
static void interact(void);
static void stop_pager(void);
#if defined(HAVE_LIBREADLINE) /*[*/
static CPPFunction attempted_completion;
static char *completion_entry(const char *, int);
#endif /*]*/
/* Pager state. */
#if !defined(_WIN32) /*[*/
static FILE *pager = NULL;
#else /*][*/
static int pager_rowcnt = 0;
static Boolean pager_q = False;
#endif /*]*/
#if !defined(_WIN32) /*[*/
/* Base keymap for c3270. */
static char *base_keymap1 =
"Ctrl<Key>]: Escape\n"
"Ctrl<Key>a Ctrl<Key>a: Key(0x01)\n"
"Ctrl<Key>a Ctrl<Key>]: Key(0x1d)\n"
"Ctrl<Key>a <Key>c: Clear\n"
"Ctrl<Key>a <Key>e: Escape\n"
"Ctrl<Key>a <Key>i: Insert\n"
"Ctrl<Key>a <Key>r: Reset\n"
"Ctrl<Key>a <Key>k: Keypad\n"
"Ctrl<Key>a <Key>l: Redraw\n"
"Ctrl<Key>a <Key>m: Compose\n"
"Ctrl<Key>a <Key>n: Menu\n"
"Ctrl<Key>a <Key>p: PrintText\n"
"Ctrl<Key>a <Key>^: Key(notsign)\n"
"<Key>DC: Delete\n"
"<Key>UP: Up\n"
"<Key>DOWN: Down\n"
"<Key>LEFT: Left\n"
"<Key>RIGHT: Right\n"
"<Key>HOME: Home\n"
"Ctrl<Key>a <Key>1: PA(1)\n"
"Ctrl<Key>a <Key>2: PA(2)\n";
static char *base_keymap2 =
"Ctrl<Key>a <Key>3: PA(3)\n"
"<Key>F1: PF(1)\n"
"Ctrl<Key>a <Key>F1: PF(13)\n"
"<Key>F2: PF(2)\n"
"Ctrl<Key>a <Key>F2: PF(14)\n"
"<Key>F3: PF(3)\n"
"Ctrl<Key>a <Key>F3: PF(15)\n"
"<Key>F4: PF(4)\n"
"Ctrl<Key>a <Key>F4: PF(16)\n"
"<Key>F5: PF(5)\n"
"Ctrl<Key>a <Key>F5: PF(17)\n"
"<Key>F6: PF(6)\n"
"Ctrl<Key>a <Key>F6: PF(18)\n";
static char *base_keymap3 =
"<Key>F7: PF(7)\n"
"Ctrl<Key>a <Key>F7: PF(19)\n"
"<Key>F8: PF(8)\n"
"Ctrl<Key>a <Key>F8: PF(20)\n"
"<Key>F9: PF(9)\n"
"Ctrl<Key>a <Key>F9: PF(21)\n"
"<Key>F10: PF(10)\n"
"Ctrl<Key>a <Key>F10: PF(22)\n"
"<Key>F11: PF(11)\n"
"Ctrl<Key>a <Key>F11: PF(23)\n"
"<Key>F12: PF(12)\n"
"Ctrl<Key>a <Key>F12: PF(24)\n";
/* Base keymap for c3270, 3270 mode. */
static char *base_3270_keymap =
"Ctrl<Key>a <Key>a: Attn\n"
"Ctrl<Key>c: Clear\n"
"Ctrl<Key>d: Dup\n"
"Ctrl<Key>f: FieldMark\n"
"Ctrl<Key>h: Erase\n"
"Ctrl<Key>i: Tab\n"
"Ctrl<Key>j: Newline\n"
"Ctrl<Key>k: Keypad\n"
"Ctrl<Key>l: Redraw\n"
"Ctrl<Key>m: Enter\n"
"Ctrl<Key>n: Menu\n"
"Ctrl<Key>r: Reset\n"
"Ctrl<Key>u: DeleteField\n"
"Ctrl<Key>a <Key>v: ToggleReverse\n"
"Ctrl<Key>a <Key>f: Flip\n"
"<Key>IC: ToggleInsert\n"
"<Key>DC: Delete\n"
"<Key>BACKSPACE: Erase\n"
"<Key>HOME: Home\n"
"<Key>END: FieldEnd\n";
#else /*][*/
/* Base keymap for wc3270. */
static char *base_keymap =
"Alt <Key>1: PA(1)\n"
"Alt <Key>2: PA(2)\n"
"Alt <Key>3: PA(3)\n"
"Alt <Key>^: Key(notsign)\n"
"Alt <Key>c: Clear\n"
"Alt <Key>C: Clear\n"
"Alt <Key>k: Keypad\n"
"Alt <Key>K: Keypad\n"
"Alt <Key>l: Redraw\n"
"Alt <Key>L: Redraw\n"
"Alt <Key>m: Compose\n"
"Alt <Key>M: Compose\n"
"Alt <Key>n: Menu\n"
"Alt <Key>N: Menu\n"
"Alt <Key>p: PrintText\n"
"Alt <Key>P: PrintText\n"
"Ctrl <Key>]: Escape\n"
"Shift <Key>F1: PF(13)\n"
"Shift <Key>F2: PF(14)\n"
"Shift <Key>F3: PF(15)\n"
"Shift <Key>F4: PF(16)\n"
"Shift <Key>F5: PF(17)\n"
"Shift <Key>F6: PF(18)\n"
"Shift <Key>F7: PF(19)\n"
"Shift <Key>F8: PF(20)\n"
"Shift <Key>F9: PF(21)\n"
"Shift <Key>F10: PF(22)\n"
"Shift <Key>F11: PF(23)\n"
"Shift <Key>F12: PF(24)\n"
"Shift <Key>ESCAPE: Key(0x1d)\n";
/* Base keymap for wc3270, 3270 mode. */
static char *base_3270_keymap =
"Ctrl <Key>a: Attn\n"
"Alt <Key>a: Attn\n"
"Alt <Key>A: Attn\n"
"Ctrl <Key>c: Clear\n"
"Ctrl <Key>d: Dup\n"
"Alt <Key>d: Dup\n"
"Alt <Key>D: Dup\n"
"Ctrl <Key>f: FieldMark\n"
"Alt <Key>f: FieldMark\n"
"Alt <Key>F: FieldMark\n"
"Ctrl <Key>h: Erase\n"
"Alt <Key>i: Insert\n"
"Alt <Key>I: Insert\n"
"Ctrl <Key>i: Tab\n"
"Ctrl <Key>j: Newline\n"
"Ctrl <Key>l: Redraw\n"
"Ctrl <Key>m: Enter\n"
"Ctrl <Key>r: Reset\n"
"Alt <Key>r: Reset\n"
"Alt <Key>R: Reset\n"
"Ctrl <Key>u: DeleteField\n"
"Ctrl <Key>v: Paste\n"
"Alt <Key>v: ToggleReverse\n"
"Alt <Key>x: Flip\n"
"<Key>INSERT: ToggleInsert\n"
"Shift <Key>TAB: BackTab\n"
"<Key>BACK: Erase\n"
"Shift <Key>END: EraseEOF\n"
"<Key>END: FieldEnd\n"
"Shift <Key>LEFT: PreviousWord\n"
"Shift <Key>RIGHT: NextWord\n"
"<Key>PRIOR: PF(7)\n"
"<Key>NEXT: PF(8)";
#endif /*]*/
Boolean any_error_output = False;
Boolean escape_pending = False;
Boolean stop_pending = False;
Boolean dont_return = False;
#if defined(_WIN32) /*[*/
char *instdir = NULL;
char *myappdata = NULL;
int is_installed;
static void start_auto_shortcut(void);
#endif /*]*/
void
usage(char *msg)
{
if (msg != CN)
fprintf(stderr, "%s\n", msg);
fprintf(stderr, "Usage: %s [options] [ps:][LUname@]hostname[:port]\n",
programname);
fprintf(stderr, "Options:\n");
cmdline_help(False);
exit(1);
}
/* Callback for connection state changes. */
static void
main_connect(Boolean ignored)
{
if (CONNECTED || appres.disconnect_clear) {
#if defined(C3270_80_132) /*[*/
if (appres.altscreen != CN)
ctlr_erase(False);
else
#endif /*]*/
ctlr_erase(True);
}
}
/* Callback for application exit. */
static void
main_exiting(Boolean ignored)
{
if (escaped)
stop_pager();
else
if (screen_suspend())
screen_final();
}
/* Make sure error messages are seen. */
static void
pause_for_errors(void)
{
char s[10];
if (any_error_output) {
screen_suspend();
printf("[Press <Enter>] ");
fflush(stdout);
if (fgets(s, sizeof(s), stdin) == NULL)
x3270_exit(1);
any_error_output = False;
}
}
#if !defined(_WIN32) /*[*/
/* Empty SIGCHLD handler, ensuring that we can collect child exit status. */
static void
sigchld_handler(int ignored)
{
#if !defined(_AIX) /*[*/
(void) signal(SIGCHLD, sigchld_handler);
#endif /*]*/
}
#endif /*]*/
int
main(int argc, char *argv[])
{
const char *cl_hostname = CN;
#if defined(_WIN32) /*[*/
char *delenv;
#endif /*]*/
#if defined(_WIN32) /*[*/
(void) get_version_info();
if (get_dirs(argv[0], "wc3270", &instdir, NULL, &myappdata,
&is_installed) < 0)
x3270_exit(1);
if (sockstart())
x3270_exit(1);
#endif /*]*/
add_resource("keymap.base",
#if defined(_WIN32) /*[*/
base_keymap
#else /*][*/
xs_buffer("%s%s%s", base_keymap1, base_keymap2, base_keymap3)
#endif /*]*/
);
add_resource("keymap.base.3270", NewString(base_3270_keymap));
argc = parse_command_line(argc, (const char **)argv, &cl_hostname);
printf("%s\n\n"
"Copyright 1989-2013 by Paul Mattes, GTRC and others.\n"
"Type 'show copyright' for full copyright information.\n"
"Type 'help' for help information.\n\n",
build);
#if defined(_WIN32) /*[*/
/* Delete the link file, if we've been told do. */
delenv = getenv(DELENV);
if (delenv != NULL) {
unlink(delenv);
putenv(DELENV "=");
}
/* Check for auto-shortcut mode. */
if (appres.auto_shortcut) {
start_auto_shortcut();
exit(0);
}
#endif /*]*/
if (charset_init(appres.charset) != CS_OKAY) {
xs_warning("Cannot find charset \"%s\"", appres.charset);
(void) charset_init(CN);
}
action_init();
#if defined(HAVE_LIBREADLINE) /*[*/
/* Set up readline. */
rl_readline_name = "c3270";
rl_initialize();
rl_attempted_completion_function = attempted_completion;
#if defined(RL_READLINE_VERSION) /*[*/
rl_completion_entry_function = completion_entry;
#else /*][*/
rl_completion_entry_function = (Function *)completion_entry;
#endif /*]*/
#endif /*]*/
/* Get the screen set up as early as possible. */
screen_init();
kybd_init();
idle_init();
keymap_init();
hostfile_init();
hostfile_init();
ansi_init();
sms_init();
register_schange(ST_CONNECT, main_connect);
register_schange(ST_3270_MODE, main_connect);
register_schange(ST_EXITING, main_exiting);
#if defined(X3270_FT) /*[*/
ft_init();
#endif /*]*/
#if defined(X3270_PRINTER) /*[*/
printer_init();
#endif /*]*/
#if !defined(_WIN32) /*[*/
/* Make sure we don't fall over any SIGPIPEs. */
(void) signal(SIGPIPE, SIG_IGN);
/* Make sure we can collect child exit status. */
(void) signal(SIGCHLD, sigchld_handler);
#endif /*]*/
/* Handle initial toggle settings. */
#if defined(X3270_TRACE) /*[*/
if (!appres.debug_tracing) {
appres.toggle[DS_TRACE].value = False;
appres.toggle[EVENT_TRACE].value = False;
}
#endif /*]*/
initialize_toggles();
icmd_init();
#if defined(HAVE_LIBSSL) /*[*/
/* Initialize SSL and ask for the password, if needed. */
ssl_base_init(NULL, NULL);
#endif /*]*/
if (cl_hostname != CN) {
pause_for_errors();
/* Connect to the host. */
appres.once = True;
if (host_connect(cl_hostname) < 0)
x3270_exit(1);
/* Wait for negotiations to complete or fail. */
while (!IN_ANSI && !IN_3270) {
(void) process_events(True);
if (!PCONNECTED)
x3270_exit(1);
if (escaped) {
printf("Connection aborted.\n");
x3270_exit(1);
}
}
pause_for_errors();
screen_disp(False);
} else {
/* Drop to the prompt. */
if (appres.secure) {
Error("Must specify hostname with secure option");
}
appres.once = False;
if (!appres.no_prompt) {
interact();
screen_disp(False);
} else
pause_for_errors();
}
peer_script_init();
/* Process events forever. */
while (1) {
if (!escaped
#if defined(X3270_FT) /*[*/
|| ft_state != FT_NONE
#endif /*]*/
)
(void) process_events(True);
if (appres.cbreak_mode && escape_pending) {
escape_pending = False;
screen_suspend();
}
if (!appres.no_prompt && !CONNECTED && !appres.reconnect) {
screen_suspend();
(void) printf("Disconnected.\n");
if (appres.once)
x3270_exit(0);
interact();
screen_resume();
} else if (escaped
#if defined(X3270_FT) /*[*/
&& ft_state == FT_NONE
#endif /*]*/
) {
interact();
trace_event("Done interacting.\n");
screen_resume();
} else if (!CONNECTED &&
!appres.reconnect &&
!appres.no_prompt) {
screen_suspend();
x3270_exit(0);
}
#if !defined(_WIN32) /*[*/
if (children && waitpid(0, (int *)0, WNOHANG) > 0)
--children;
#else /*][*/
printer_check();
#endif /*]*/
screen_disp(False);
}
}
#if !defined(_WIN32) /*[*/
/*
* SIGTSTP handler for use while a command is running. Sets a flag so that
* c3270 will stop before the next prompt is printed.
*/
static void
running_sigtstp_handler(int ignored _is_unused)
{
signal(SIGTSTP, SIG_IGN);
stop_pending = True;
}
/*
* SIGTSTP haandler for use while the prompt is being displayed.
* Acts immediately by setting SIGTSTP to the default and sending it to
* ourselves, but also sets a flag so that the user gets one free empty line
* of input before resuming the connection.
*/
static void
prompt_sigtstp_handler(int ignored _is_unused)
{
if (CONNECTED)
dont_return = True;
signal(SIGTSTP, SIG_DFL);
kill(getpid(), SIGTSTP);
}
#endif /*]*/
/*static*/ void
interact(void)
{
/* In case we got here because a command output, stop the pager. */
stop_pager();
trace_event("Interacting.\n");
if (appres.secure || appres.no_prompt) {
char s[10];
printf("[Press <Enter>] ");
fflush(stdout);
if (fgets(s, sizeof(s), stdin) == NULL)
x3270_exit(1);
return;
}
#if !defined(_WIN32) /*[*/
/* Handle SIGTSTP differently at the prompt. */
signal(SIGTSTP, SIG_DFL);
#endif /*]*/
/*
* Ignore SIGINT at the prompt.
* I'm sure there's more we could do.
*/
signal(SIGINT, SIG_IGN);
for (;;) {
int sl;
char *s;
#if defined(HAVE_LIBREADLINE) /*[*/
char *rl_s;
#else /*][*/
char buf[1024];
#endif /*]*/
dont_return = False;
/* Process a pending stop now. */
if (stop_pending) {
stop_pending = False;
#if !defined(_WIN32) /*[*/
signal(SIGTSTP, SIG_DFL);
kill(getpid(), SIGTSTP);
#endif /*]*/
continue;
}
#if !defined(_WIN32) /*[*/
/* Process SIGTSTPs immediately. */
signal(SIGTSTP, prompt_sigtstp_handler);
#endif /*]*/
/* Display the prompt. */
if (CONNECTED)
(void) printf("Press <Enter> to resume session.\n");
#if defined(HAVE_LIBREADLINE) /*[*/
s = rl_s = readline("c3270> ");
if (s == CN) {
printf("\n");
exit(0);
}
#else /*][*/
(void) printf(PROGRAM_NAME "> ");
(void) fflush(stdout);
/* Get the command, and trim white space. */
if (fgets(buf, sizeof(buf), stdin) == CN) {
printf("\n");
#if defined(_WIN32) /*[*/
continue;
#else /*][*/
x3270_exit(0);
#endif /*]*/
}
s = buf;
#endif /*]*/
#if !defined(_WIN32) /*[*/
/* Defer SIGTSTP until the next prompt display. */
signal(SIGTSTP, running_sigtstp_handler);
#endif /*]*/
while (isspace(*s))
s++;
sl = strlen(s);
while (sl && isspace(s[sl-1]))
s[--sl] = '\0';
/* A null command means go back. */
if (!sl) {
if (CONNECTED && !dont_return)
break;
else
continue;
}
#if defined(HAVE_LIBREADLINE) /*[*/
/* Save this command in the history buffer. */
add_history(s);
#endif /*]*/
/* "?" is an alias for "Help". */
if (!strcmp(s, "?"))
s = "Help";
/*
* Process the command like a macro, and spin until it
* completes.
*/
push_command(s);
while (sms_active()) {
(void) process_events(True);
}
/* Close the pager. */
stop_pager();
#if defined(HAVE_LIBREADLINE) /*[*/
/* Give back readline's buffer. */
free(rl_s);
#endif /*]*/
/* If it succeeded, return to the session. */
if (!macro_output && CONNECTED)
break;
}
/* Ignore SIGTSTP again. */
stop_pending = False;
#if !defined(_WIN32) /*[*/
signal(SIGTSTP, SIG_IGN);
#endif /*]*/
#if defined(_WIN32) /*[*/
signal(SIGINT, SIG_DFL);
#endif /*]*/
}
/* A command is about to produce output. Start the pager. */
FILE *
start_pager(void)
{
#if !defined(_WIN32) /*[*/
static char *lesspath = LESSPATH;
static char *lesscmd = LESSPATH " -EX";
static char *morepath = MOREPATH;
static char *or_cat = " || cat";
char *pager_env;
char *pager_cmd = CN;
if (pager != NULL)
return pager;
if ((pager_env = getenv("PAGER")) != CN)
pager_cmd = pager_env;
else if (strlen(lesspath))
pager_cmd = lesscmd;
else if (strlen(morepath))
pager_cmd = morepath;
if (pager_cmd != CN) {
char *s;
s = Malloc(strlen(pager_cmd) + strlen(or_cat) + 1);
(void) sprintf(s, "%s%s", pager_cmd, or_cat);
pager = popen(s, "w");
Free(s);
if (pager == NULL)
(void) perror(pager_cmd);
}
if (pager == NULL)
pager = stdout;
return pager;
#else /*][*/
return stdout;
#endif /*]*/
}
/* Stop the pager. */
static void
stop_pager(void)
{
#if !defined(_WIN32) /*[*/
if (pager != NULL) {
if (pager != stdout)
pclose(pager);
pager = NULL;
}
#else /*][*/
pager_rowcnt = 0;
pager_q = False;
#endif /*]*/
}
#if defined(_WIN32) /*[*/
void
pager_output(const char *s)
{
if (pager_q)
return;
do {
char *nl;
int sl;
/* Pause for a screenful. */
if (pager_rowcnt >= maxROWS) {
printf("Press any key to continue . . . ");
fflush(stdout);
pager_q = screen_wait_for_key(NULL);
printf("\r \r");
pager_rowcnt = 0;
if (pager_q)
return;
}
/*
* Look for an embedded newline. If one is found, just print
* up to it, so we can count the newline and possibly pause
* partway through the string.
*/
nl = strchr(s, '\n');
if (nl != CN) {
sl = nl - s;
printf("%.*s\n", sl, s);
s = nl + 1;
} else {
printf("%s\n", s);
sl = strlen(s);
s = CN;
}
/* Account for the newline. */
pager_rowcnt++;
/* Account (conservatively) for any line wrap. */
pager_rowcnt += sl / maxCOLS;
} while (s != CN);
}
#endif /*]*/
#if defined(HAVE_LIBREADLINE) /*[*/
static char **matches = (char **)NULL;
static char **next_match;
/* Generate a match list. */
static char **
attempted_completion(const char *text, int start, int end)
{
char *s;
int i, j;
int match_count;
/* If this is not the first word, fail. */
s = rl_line_buffer;
while (*s && isspace(*s))
s++;
if (s - rl_line_buffer < start) {
char *t = s;
struct host *h;
/*
* If the first word is 'Connect' or 'Open', and the
* completion is on the second word, expand from the
* hostname list.
*/
/* See if we're in the second word. */
while (*t && !isspace(*t))
t++;
while (*t && isspace(*t))
t++;
if (t - rl_line_buffer < start)
return NULL;
/*
* See if the first word is 'Open' or 'Connect'. In future,
* we might do other expansions, and this code would need to
* be generalized.
*/
if (!((!strncasecmp(s, "Open", 4) && isspace(*(s + 4))) ||
(!strncasecmp(s, "Connect", 7) && isspace(*(s + 7)))))
return NULL;
/* Look for any matches. Note that these are case-sensitive. */
for (h = hosts, match_count = 0; h; h = h->next) {
if (!strncmp(h->name, t, strlen(t)))
match_count++;
}
if (!match_count)
return NULL;
/* Allocate the return array. */
next_match = matches =
Malloc((match_count + 1) * sizeof(char **));
/* Scan again for matches to fill in the array. */
for (h = hosts, j = 0; h; h = h->next) {
int skip = 0;
if (strncmp(h->name, t, strlen(t)))
continue;
/*
* Skip hostsfile entries that are duplicates of
* RECENT entries we've already recorded.
*/
if (h->entry_type != RECENT) {
for (i = 0; i < j; i++) {
if (!strcmp(matches[i],
h->name)) {
skip = 1;
break;
}
}
}
if (skip)
continue;
/*
* If the string contains spaces, put it in double
* quotes. Otherwise, just copy it. (Yes, this code
* is fairly stupid, and can be fooled by other
* whitespace and embedded double quotes.)
*/
if (strchr(h->name, ' ') != CN) {
matches[j] = Malloc(strlen(h->name) + 3);
(void) sprintf(matches[j], "\"%s\"", h->name);
j++;
} else {
matches[j++] = NewString(h->name);
}
}
matches[j] = CN;
return NULL;
}
/* Search for matches. */
for (i = 0, match_count = 0; i < actioncount; i++) {
if (!strncasecmp(actions[i].string, s, strlen(s)))
match_count++;
}
if (!match_count)
return NULL;
/* Return what we got. */
next_match = matches = Malloc((match_count + 1) * sizeof(char **));
for (i = 0, j = 0; i < actioncount; i++) {
if (!strncasecmp(actions[i].string, s, strlen(s))) {
matches[j++] = NewString(actions[i].string);
}
}
matches[j] = CN;
return NULL;
}
/* Return the match list. */
static char *
completion_entry(const char *text, int state)
{
char *r;
if (next_match == NULL)
return CN;
if ((r = *next_match++) == CN) {
Free(matches);
next_match = matches = NULL;
return CN;
} else
return r;
}
#endif /*]*/
/* c3270-specific actions. */
/* Return a time difference in English */
static char *
hms(time_t ts)
{
time_t t, td;
long hr, mn, sc;
static char buf[128];
(void) time(&t);
td = t - ts;
hr = td / 3600;
mn = (td % 3600) / 60;
sc = td % 60;
if (hr > 0)
(void) sprintf(buf, "%ld %s %ld %s %ld %s",
hr, (hr == 1) ?
get_message("hour") : get_message("hours"),
mn, (mn == 1) ?
get_message("minute") : get_message("minutes"),
sc, (sc == 1) ?
get_message("second") : get_message("seconds"));
else if (mn > 0)
(void) sprintf(buf, "%ld %s %ld %s",
mn, (mn == 1) ?
get_message("minute") : get_message("minutes"),
sc, (sc == 1) ?
get_message("second") : get_message("seconds"));
else
(void) sprintf(buf, "%ld %s",
sc, (sc == 1) ?
get_message("second") : get_message("seconds"));
return buf;
}
static void
status_dump(void)
{
const char *emode, *ftype, *ts;
#if defined(X3270_TN3270E) /*[*/
const char *eopts;
const char *bplu;
#endif /*]*/
const char *ptype;
extern int linemode; /* XXX */
extern time_t ns_time;
extern int ns_bsent, ns_rsent, ns_brcvd, ns_rrcvd;
action_output("%s", build);
action_output("%s %s: %d %s x %d %s, %s, %s",
get_message("model"), model_name,
maxCOLS, get_message("columns"),
maxROWS, get_message("rows"),
appres.m3279? get_message("fullColor"): get_message("mono"),
(appres.extended && !std_ds_host) ? get_message("extendedDs") :
get_message("standardDs"));
action_output("%s %s", get_message("terminalName"), termtype);
if (connected_lu != CN && connected_lu[0])
action_output("%s %s", get_message("luName"), connected_lu);
#if defined(X3270_TN3270E) /*[*/
bplu = net_query_bind_plu_name();
if (bplu != CN && bplu[0])
action_output("%s %s", get_message("bindPluName"), bplu);
#endif /*]*/
action_output("%s %s (%s)", get_message("characterSet"),
get_charset_name(),
#if defined(X3270_DBCS) /*[*/
dbcs? "DBCS": "SBCS"
#else /*][*/
"SBCS"
#endif /*]*/
);
action_output("%s %s",
get_message("hostCodePage"),
get_host_codepage());
action_output("%s GCSGID %u, CPGID %u",
get_message("sbcsCgcsgid"),
(unsigned short)((cgcsgid >> 16) & 0xffff),
(unsigned short)(cgcsgid & 0xffff));
#if defined(X3270_DBCS) /*[*/
if (dbcs)
action_output("%s GCSGID %u, CPGID %u",
get_message("dbcsCgcsgid"),
(unsigned short)((cgcsgid_dbcs >> 16) & 0xffff),
(unsigned short)(cgcsgid_dbcs & 0xffff));
#endif /*]*/
#if !defined(_WIN32) /*[*/
action_output("%s %s", get_message("localeCodeset"), locale_codeset);
action_output("%s DBCS %s, wide curses %s",
get_message("buildOpts"),
#if defined(X3270_DBCS) /*[*/
get_message("buildEnabled"),
#else /*][*/
get_message("buildDisabled"),
#endif /*]*/
#if defined(CURSES_WIDE) /*[*/
get_message("buildEnabled")
#else /*][*/
get_message("buildDisabled")
#endif /*]*/
);
#else /*][*/
action_output("%s OEM %d ANSI %d", get_message("windowsCodePage"),
windows_cp, GetACP());
#endif /*]*/
if (appres.key_map) {
action_output("%s %s", get_message("keyboardMap"),
appres.key_map);
}
if (CONNECTED) {
action_output("%s %s",
get_message("connectedTo"),
#if defined(LOCAL_PROCESS) /*[*/
(local_process && !strlen(current_host))? "(shell)":
#endif /*]*/
current_host);
#if defined(LOCAL_PROCESS) /*[*/
if (!local_process) {
#endif /*]*/
action_output(" %s %d", get_message("port"),
current_port);
#if defined(LOCAL_PROCESS) /*[*/
}
#endif /*]*/
#if defined(HAVE_LIBSSL) /*[*/
if (secure_connection) {
action_output(" %s%s%s", get_message("secure"),
secure_unverified? ", ": "",
secure_unverified? get_message("unverified"): "");
if (secure_unverified) {
int i;
for (i = 0; unverified_reasons[i] != CN; i++) {
action_output(" %s",
unverified_reasons[i]);
}
}
}
#endif /*]*/
ptype = net_proxy_type();
if (ptype) {
action_output(" %s %s %s %s %s %s",
get_message("proxyType"), ptype,
get_message("server"), net_proxy_host(),
get_message("port"), net_proxy_port());
}
ts = hms(ns_time);
if (IN_E)
emode = "TN3270E ";
else
emode = "";
if (IN_ANSI) {
if (linemode)
ftype = get_message("lineMode");
else
ftype = get_message("charMode");
action_output(" %s%s, %s", emode, ftype, ts);
} else if (IN_SSCP) {
action_output(" %s%s, %s", emode,
get_message("sscpMode"), ts);
} else if (IN_3270) {
action_output(" %s%s, %s", emode,
get_message("dsMode"), ts);
} else
action_output(" %s, %s",
get_message("unnegotiated"), ts);
#if defined(X3270_TN3270E) /*[*/
eopts = tn3270e_current_opts();
if (eopts != CN) {
action_output(" %s %s", get_message("tn3270eOpts"),
eopts);
} else if (IN_E) {
action_output(" %s", get_message("tn3270eNoOpts"));
}
#endif /*]*/
if (IN_3270)
action_output("%s %d %s, %d %s\n%s %d %s, %d %s",
get_message("sent"),
ns_bsent, (ns_bsent == 1) ?
get_message("byte") : get_message("bytes"),
ns_rsent, (ns_rsent == 1) ?
get_message("record") : get_message("records"),
get_message("Received"),
ns_brcvd, (ns_brcvd == 1) ?
get_message("byte") : get_message("bytes"),
ns_rrcvd, (ns_rrcvd == 1) ?
get_message("record") : get_message("records"));
else
action_output("%s %d %s, %s %d %s",
get_message("sent"),
ns_bsent, (ns_bsent == 1) ?
get_message("byte") : get_message("bytes"),
get_message("received"),
ns_brcvd, (ns_brcvd == 1) ?
get_message("byte") : get_message("bytes"));
#if defined(X3270_ANSI) /*[*/
if (IN_ANSI) {
struct ctl_char *c = net_linemode_chars();
int i;
char buf[128];
char *s = buf;
action_output("%s", get_message("specialCharacters"));
for (i = 0; c[i].name; i++) {
if (i && !(i % 4)) {
*s = '\0';
action_output("%s", buf);
s = buf;
}
s += sprintf(s, " %s %s", c[i].name,
c[i].value);
}
if (s != buf) {
*s = '\0';
action_output("%s", buf);
}
}
#endif /*]*/
} else if (HALF_CONNECTED) {
action_output("%s %s", get_message("connectionPending"),
current_host);
} else
action_output("%s", get_message("notConnected"));
}
static void
copyright_dump(void)
{
action_output(" ");
action_output("%s", build);
action_output(" ");
action_output("Copyright (c) 1993-2013, Paul Mattes.");
action_output("Copyright (c) 1990, Jeff Sparkes.");
action_output("Copyright (c) 1989, Georgia Tech Research Corporation (GTRC), Atlanta, GA");
action_output(" 30332.");
action_output("All rights reserved.");
action_output(" ");
action_output("Redistribution and use in source and binary forms, with or without");
action_output("modification, are permitted provided that the following conditions are met:");
action_output(" * Redistributions of source code must retain the above copyright");
action_output(" notice, this list of conditions and the following disclaimer.");
action_output(" * Redistributions in binary form must reproduce the above copyright");
action_output(" notice, this list of conditions and the following disclaimer in the");
action_output(" documentation and/or other materials provided with the distribution.");
action_output(" * Neither the names of Paul Mattes, Jeff Sparkes, GTRC nor the names of");
action_output(" their contributors may be used to endorse or promote products derived");
action_output(" from this software without specific prior written permission.");
action_output(" ");
action_output("THIS SOFTWARE IS PROVIDED BY PAUL MATTES, JEFF SPARKES AND GTRC \"AS IS\" AND");
action_output("ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE");
action_output("IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE");
action_output("ARE DISCLAIMED. IN NO EVENT SHALL PAUL MATTES, JEFF SPARKES OR GTRC BE");
action_output("LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR");
action_output("CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF");
action_output("SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS");
action_output("INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN");
action_output("CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)");
action_output("ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE");
action_output("POSSIBILITY OF SUCH DAMAGE.");
action_output(" ");
}
void
Show_action(Widget w _is_unused, XEvent *event _is_unused, String *params,
Cardinal *num_params)
{
action_debug(Show_action, event, params, num_params);
if (*num_params == 0) {
action_output(" Show copyright copyright information");
action_output(" Show stats connection statistics");
action_output(" Show status same as 'Show stats'");
action_output(" Show keymap current keymap");
return;
}
if (!strncasecmp(params[0], "stats", strlen(params[0])) ||
!strncasecmp(params[0], "status", strlen(params[0]))) {
status_dump();
} else if (!strncasecmp(params[0], "keymap", strlen(params[0]))) {
keymap_dump();
} else if (!strncasecmp(params[0], "copyright", strlen(params[0]))) {
copyright_dump();
} else
popup_an_error("Unknown 'Show' keyword");
}
#if defined(X3270_TRACE) /*[*/
/* Trace([data|keyboard][on [filename]|off]) */
void
Trace_action(Widget w _is_unused, XEvent *event _is_unused, String *params,
Cardinal *num_params)
{
int tg = 0;
Boolean both = False;
Boolean on = False;
action_debug(Trace_action, event, params, num_params);
if (*num_params == 0) {
action_output("Data tracing is %sabled.",
toggled(DS_TRACE)? "en": "dis");
action_output("Keyboard tracing is %sabled.",
toggled(EVENT_TRACE)? "en": "dis");
return;
}
if (!strcasecmp(params[0], "Data"))
tg = DS_TRACE;
else if (!strcasecmp(params[0], "Keyboard"))
tg = EVENT_TRACE;
else if (!strcasecmp(params[0], "Off")) {
both = True;
on = False;
if (*num_params > 1) {
popup_an_error("Trace(): Too many arguments for 'Off'");
return;
}
} else if (!strcasecmp(params[0], "On")) {
both = True;
on = True;
} else {
popup_an_error("Trace(): Unknown trace type -- "
"must be Data or Keyboard");
return;
}
if (!both) {
if (*num_params == 1 || !strcasecmp(params[1], "On"))
on = True;
else if (!strcasecmp(params[1], "Off")) {
on = False;
if (*num_params > 2) {
popup_an_error("Trace(): Too many arguments "
"for 'Off'");
return;
}
} else {
popup_an_error("Trace(): Must be 'On' or 'Off'");
return;
}
}
if (both) {
if (on && *num_params > 1)
trace_set_trace_file(params[1]);
if ((on && !toggled(DS_TRACE)) || (!on && toggled(DS_TRACE)))
do_toggle(DS_TRACE);
if ((on && !toggled(EVENT_TRACE)) ||
(!on && toggled(EVENT_TRACE)))
do_toggle(EVENT_TRACE);
} else if ((on && !toggled(tg)) || (!on && toggled(tg))) {
if (on && *num_params > 2)
trace_set_trace_file(params[2]);
do_toggle(tg);
}
if (tracefile_name != NULL)
action_output("Trace file is %s", tracefile_name);
}
/* ScreenTrace(on [filename]|off) */
void
ScreenTrace_action(Widget w _is_unused, XEvent *event _is_unused,
String *params, Cardinal *num_params)
{
Boolean on = False;
action_debug(Trace_action, event, params, num_params);
if (*num_params == 0) {
action_output("Screen tracing is %sabled.",
toggled(SCREEN_TRACE)? "en": "dis");
return;
}
if (!strcasecmp(params[0], "On")) {
on = True;
} else if (!strcasecmp(params[0], "Off")) {
on = False;
if (*num_params > 1) {
popup_an_error("ScreenTrace(): Too many arguments "
"for 'Off'");
return;
}
} else {
popup_an_error("ScreenTrace(): Must be 'On' or 'Off'");
return;
}
if ((on && !toggled(SCREEN_TRACE)) || (!on && toggled(SCREEN_TRACE))) {
if (on && *num_params > 1)
trace_set_screentrace_file(params[1]);
do_toggle(SCREEN_TRACE);
}
if (screentracefile_name != NULL)
action_output("Trace file is %s", screentracefile_name);
}
#endif /*]*/
/* Break to the command prompt. */
void
Escape_action(Widget w _is_unused, XEvent *event _is_unused, String *params _is_unused,
Cardinal *num_params _is_unused)
{
action_debug(Escape_action, event, params, num_params);
if (!appres.secure && !appres.no_prompt) {
host_cancel_reconnect();
screen_suspend();
#if defined(X3270_SCRIPT) /*[*/
abort_script();
#endif /*]*/
}
}
/* Popup an informational message. */
void
popup_an_info(const char *fmt, ...)
{
va_list args;
static char vmsgbuf[4096];
char *s, *t;
Boolean quoted = False;
va_start(args, fmt);
(void) vsprintf(vmsgbuf, fmt, args);
va_end(args);
/* Filter out the junk. */
for (s = t = vmsgbuf; *s; s++) {
if (*s == '\n') {
*t = '\0';
break;
} else if (!quoted && *s == '\\') {
quoted = True;
} else {
*t++ = *s;
quoted = False;
}
}
*t = '\0';
if (strlen(vmsgbuf))
status_push(vmsgbuf);
}
void
Info_action(Widget w _is_unused, XEvent *event _is_unused, String *params,
Cardinal *num_params)
{
action_debug(Info_action, event, params, num_params);
if (!*num_params)
return;
popup_an_info("%s", params[0]);
}
#if !defined(_WIN32) /*[*/
/* Support for c3270 profiles. */
#define PROFILE_ENV "C3270PRO"
#define NO_PROFILE_ENV "NOC3270PRO"
#define DEFAULT_PROFILE "~/.c3270pro"
/* Read in the .c3270pro file. */
Boolean
merge_profile(void)
{
const char *fname;
char *profile_name;
Boolean did_read = False;
/* Check for the no-profile environment variable. */
if (getenv(NO_PROFILE_ENV) != CN)
return did_read;
/* Read the file. */
fname = getenv(PROFILE_ENV);
if (fname == CN || *fname == '\0')
fname = DEFAULT_PROFILE;
profile_name = do_subst(fname, True, True);
did_read = (read_resource_file(profile_name, False) >= 0);
Free(profile_name);
return did_read;
}
#endif /*]*/
#if defined(_WIN32) /*[*/
/* Start a auto-shortcut-mode copy of wc3270.exe. */
static void
start_auto_shortcut(void)
{
char *tempdir;
FILE *f;
session_t s;
HRESULT hres;
char exepath[MAX_PATH];
char linkpath[MAX_PATH];
char sesspath[MAX_PATH];
char delenv[32 + MAX_PATH];
char args[1024];
HINSTANCE h;
extern char *profile_path; /* XXX */
/* Make sure we're on NT. */
if (!is_nt) {
fprintf(stderr, "Auto-shortcut does not work on Win9x\n");
x3270_exit(1);
}
/* Make sure there is a session file. */
if (profile_path == CN) {
fprintf(stderr, "Can't use auto-shortcut mode without a "
"session file\n");
x3270_exit(1);
}
printf("Running auto-shortcut\n"); fflush(stdout);
/* Read the session file into 's'. */
f = fopen(profile_path, "r");
if (f == NULL) {
fprintf(stderr, "%s: %s\n", profile_path, strerror(errno));
x3270_exit(1);
}
memset(&s, '\0', sizeof(session_t));
if (read_session(f, &s) == 0) {
fprintf(stderr, "%s: invalid format\n", profile_path);
x3270_exit(1);
}
printf("Read in session '%s'\n", profile_path); fflush(stdout);
/* Create the shortcut. */
tempdir = getenv("TEMP");
if (tempdir == CN) {
fprintf(stderr, "No %%TEMP%%?\n");
x3270_exit(1);
}
sprintf(linkpath, "%s\\wcsa%u.lnk", tempdir, getpid());
sprintf(exepath, "%s\\%s", instdir, "wc3270.exe");
printf("Executable path is '%s'\n", exepath); fflush(stdout);
if (GetFullPathName(profile_path, MAX_PATH, sesspath, NULL) == 0) {
fprintf(stderr, "%s: Error %ld\n", profile_path,
GetLastError());
x3270_exit(1);
}
sprintf(args, "+S \"%s\"", sesspath);
hres = create_shortcut(&s, /* session */
exepath, /* .exe */
linkpath, /* .lnk */
args, /* args */
tempdir /* cwd */);
if (!SUCCEEDED(hres)) {
fprintf(stderr, "Cannot create ShellLink '%s'\n", linkpath);
x3270_exit(1);
}
printf("Created ShellLink '%s'\n", linkpath); fflush(stdout);
/* Execute it. */
sprintf(delenv, "%s=%s", DELENV, linkpath);
putenv(delenv);
h = ShellExecute(NULL, "open", linkpath, "", tempdir, SW_SHOW);
if ((int)h <= 32) {
fprintf(stderr, "ShellExecute failed, error %d\n", (int)h);
x3270_exit(1);
}
printf("Started ShellLink\n"); fflush(stdout);
exit(0);
}
#endif /*]*/
| [
"[email protected]"
] | |
8058be500a8d8a269abd6ae2bfc130c83176760b | 7653d2d6d14e258b8e7fba127767eedb70306f2c | /src/libraries/hal/platform-i386/ports.c | 61d2a12999f234fd1944ddf25e0ff2c748300165 | [
"MIT"
] | permissive | awooos/awooos | 81a9d2f8843e070489699a6ed7929b50341dab7e | 77fe08d01aede2b4e928a5d172b31da0fb91f44e | refs/heads/master | 2023-05-12T12:37:25.260879 | 2022-02-13T07:48:52 | 2022-02-13T07:48:52 | 104,856,058 | 36 | 8 | MIT | 2022-02-13T07:51:06 | 2017-09-26T08:13:58 | C | UTF-8 | C | false | false | 445 | c | #include "ports.h"
#include <stdint.h>
void hal_outb(uint16_t port, uint8_t value)
{
__asm__ __volatile__ ("outb %0, %1" : : "a" (value), "dN" (port));
}
uint8_t hal_inb(uint16_t port)
{
uint8_t value;
__asm__ volatile ("inb %1, %0" : "=a" (value) : "dN" (port));
return value;
}
uint16_t hal_inw(uint16_t port)
{
uint16_t value;
__asm__ volatile ("inw %1, %0" : "=a" (value) : "dN" (port));
return value;
}
| [
"[email protected]"
] | |
50328adaf2055f9eb0f0a11d7c16e60078124e2e | 788178767f2959d1bdb833f51acbb0eb76fd1787 | /strtow.c | ce06971f4ed3751cedf92f291b4362a3aaee2b84 | [] | no_license | ogoigbe12/monty | 84d7931689b272732266d6d1d335af6812741bbb | d0dd326240190244570279b4dc7794df6433cb9b | refs/heads/master | 2023-08-04T23:09:07.035707 | 2021-09-23T09:15:58 | 2021-09-23T09:15:58 | 408,744,764 | 0 | 0 | null | null | null | null | UTF-8 | C | false | false | 1,437 | c | #include "monty.h"
#include "lists.h"
/**
* count_word - helper function to count the number of words in a string
* @s: string to evaluate
*
* Return: number of words
*/
int count_word(char *s)
{
int flag, c, w;
flag = 0;
w = 0;
for (c = 0; s[c] != '\0'; c++)
{
if (s[c] == ' ')
flag = 0;
else if (flag == 0)
{
flag = 1;
w++;
}
}
return (w);
}
/**
* **strtow - splits a string into words
* @str: string to split
*
* Return: pointer to an array of strings (Success)
* or NULL (Error)
*/
char **strtow(char *str)
{
char **matrix, *tmp;
int i, k = 0, len = 0, words, c = 0, start, end;
len = strlen(str);
words = count_word(str);
if (words == 0)
return (NULL);
matrix = (char **) malloc(sizeof(char *) * (words + 1));
if (matrix == NULL)
return (NULL);
for (i = 0; i <= len; i++)
{
if (isspace(str[i]) || str[i] == '\0' || str[i] == '\n')
{
if (c)
{
end = i;
tmp = (char *) malloc(sizeof(char) * (c + 1));
if (tmp == NULL)
return (NULL);
while (start < end)
*tmp++ = str[start++];
*tmp = '\0';
matrix[k] = tmp - c;
k++;
c = 0;
}
}
else if (c++ == 0)
start = i;
}
matrix[k] = NULL;
return (matrix);
}
/**
* free_everything - frees arrays of strings
* @args: array of strings to free
*/
void free_everything(char **args)
{
int i;
if (!args)
return;
for (i = 0; args[i]; i++)
free(args[i]);
free(args);
}
| [
"[email protected]"
] | |
c1dbcb23971a131e322afe520b77aac94c55b2b9 | 8a3791b34b38ae96740730902d86b88d87541d91 | /week7/dllib/error1.c | b94f9d748ad4f05ad4d5897dfc57563eba83b78f | [] | no_license | if-else-try/LinuxL | 9e17c91c54f42d75f8ab839bc6e35badfa41fbd6 | e333035063cf276bdffae83a749ef322f1bfc161 | refs/heads/master | 2023-01-31T01:06:19.081055 | 2020-12-19T12:04:22 | 2020-12-19T12:04:22 | 299,923,796 | 0 | 0 | null | null | null | null | UTF-8 | C | false | false | 117 | c | #include"../ch7.h"
int *p;
int main()
{
int *q;
*p = 1;
*q = 2;
printf("*p = %d,*q = %d\n",*p,*q);
return 0;
}
| [
"[email protected]"
] | |
6a03488e1830e727573f55f14b2efcedaa76152c | 27bcd5c9ded70102540c0ccd03f3e2b281dbf58c | /mudlib/std/antiguo/spells/examples/sym_spel.c | eba9f1d4916e9395deb5752cb722bbc20c0d58b7 | [] | no_license | unleashed/ninetears | 57fdc71fd651b3ff95e5e7c14b0566729584e006 | 4edd22c75e3fa99be4b5820300491c6b62e06085 | refs/heads/master | 2020-07-14T04:25:56.302027 | 2019-08-29T18:46:57 | 2019-08-29T18:46:57 | 205,225,438 | 1 | 0 | null | null | null | null | UTF-8 | C | false | false | 5,443 | c | /*** Symbol Transformation ***/
/*** NPC friendly, coded by Wonderflug ***/
#include "tweaks.h"
inherit "/std/spells/base.c";
#define SP_NAME "Symbol Transformation"
#define SPELLTYPE "offensive"
#define SPELLPATH "/std/spells/cleric/"
void setup()
{
set_spell_name("Symbol Transformation");
set_spell_level(7);
set_sphere("summoning");
set_target_type("none");
set_range(0);
set_help_desc("This spell is granted only to the most faithful of a deities' "
"worshippers. The effects, cost, and duration vary according to the "
"deity of the cleric. A holy symbol is required and in some cases "
"consumed in the casting.");
set_gp_cost(0);
set_casting_time(3);
set_rounds( ({ "round1", "round2", "round3" }) );
}
/* Yes, we need to overload this, alas */
string help()
{
string str;
str = ::help();
switch( (string)this_player()->query_guild_name() )
{
case "Cyrcia":
str += " For worshippers of Cyrcia, your "
"holy symbol grows and animates into a Massive "
"spider. The spider will follow and protect "
"you, staying around for at most 1 turn "
"per level. At this time it will revert back into "
"your holy symbol. If, however, the spider is "
"killed, your symbol will not be recovered. Additionally, "
"you may 'dismiss spider', to cause the spider to immediately "
"revert back into your holy symbol.\n"
"GP cost: 15";
break;
case "Ducky":
str += " The Eye of Ducky rots and brings forth a death maggot "
"which wil defend the summoner. If the maggot dies, the symbol "
"cannot be recovered, otherwise it will in time, vomit forth "
"an eye which it hides in again. You may also dismiss the "
"maggot.\n"
"GP cost: 15";
break;
case "hokemj":
str += " For Hokemj's followers, your holy symbol will fracture into "
"four leaves, which array around you and block damage from attacks. "
"They will last for 1 round / level, and block 4*level HP worth "
"of damage. When both of these conditions have occurred, the "
"leaves will revert back into your holy symbol. \n"
"GP Cost: 20 \n"
"NOTE: if you don't have the available encumbrance, or you quit "
"while the leaves are still on, you will (probably) not get your "
"holy symbol back.";
break;
case "timion":
str += " For worshippers of Timion, your holy symbol will "
"grow into a massive enchanted Hammer. The power of "
"the enchant will be +1 per 6 levels of the caster, to a "
"maximum of +5. The hammer will only be "
"effective in the hands of the faithful of Timion, and "
"will not save. The holy symbol is utterly consumed in the "
"casting. The damage done will always increase with level.\n"
"GP Cost: 14 GP";
break;
default:
break;
}
return str+"\n\n";
}
int round1(object caster, mixed target, mixed out_range, int time, int quiet)
{
tell_object(caster, "You make somantic gestures while chanting "
"softly.\n");
tell_room(environment(caster), caster->query_cap_name()+" makes "
"somantic gestures while chanting softly.\n", caster);
return 0;
}
int round2(object caster, mixed target, mixed out_range, int time, int quiet)
{
tell_room(environment(caster), caster->query_cap_name()+" raises "+
caster->query_possessive()+" holy symbol, shouting syllables "
"of faith and devotion.\n", caster);
tell_object(caster, "You raise your holy symbol, shouting out "
"syllables of faith and devotion.\n");
return 0;
}
int round3(object caster, mixed target, mixed out_range, int time, int quiet)
{
int i, has_symbol;
string faith;
mixed symbol;
string symfile;
object sym;
int cost;
/* Do holy symbol check here */
faith = (string)caster->query_guild_name();
symbol = find_match("holy symbols", caster);
if ( !sizeof(symbol) )
{
tell_object(caster, "You need a holy symbol to cast this spell.\n");
return 0;
}
has_symbol = 0;
for (i=0;i<sizeof(symbol);i++)
if ( (string)symbol[i]->query_property("faith") == faith )
{
symbol = symbol[i];
has_symbol = 1;
break;
}
if ( !has_symbol )
{
tell_object(caster, "You need a holy symbol to cast this spell.\n");
return 0;
}
switch ( faith )
{
case "Ducky":
case "Cyrcia":
cost = 15;
break;
case "hokemj":
if (caster->query_skin_spell())
{
tell_object(caster, "You cannot complete this spell right now.\n");
tell_room(environment(caster), caster->query_cap_name()+
" stops casting.\n", caster);
return 0;
}
cost = 20;
break;
case "taniwha":
cost = 10;
break;
case "timion":
cost = 14;
break;
default:
break;
}
if ((int)caster->query_gp() < cost )
{
tell_object(caster,"You are too mentally drained to complete "
"this spell.\n");
tell_room(environment(caster), caster->query_cap_name()+" stops "
"casting.\n", caster);
return 0;
}
caster->adjust_gp(-cost);
symfile = SPELLPATH+"sym_"+lower_case(faith)+".c";
catch(sym=clone_object(symfile));
if(!sym)
{
write("Ooops something broke, 'mail spells'.\n");
return 0;
}
sym->setup_spell(caster);
symbol->dest_me();
return 0;
}
| [
"[email protected]"
] | |
33f7a5bec3f918f2c18fa3ca512abbb96c8cbd6b | b8c235adf05679142afdf0495aec7d5bc8bbe343 | /tests/test-aux8-pngread.c | 6a7428c3ce76d62027c45abf59ec625ce5a5483e | [
"MIT"
] | permissive | codylico/png-parts | 803a667f72efe7e2e27623236532b6e6cf47b2f2 | f3f5997e6c9f19f7c6aaaffa7929675b76eada1d | refs/heads/master | 2023-01-13T16:57:54.293676 | 2021-10-26T19:58:56 | 2021-10-26T19:58:56 | 129,463,494 | 0 | 1 | MIT | 2021-06-06T22:18:02 | 2018-04-13T23:27:25 | C | UTF-8 | C | false | false | 5,317 | c | /*
* PNG-parts
* parts of a Portable Network Graphics implementation
* Copyright 2018-2019 Cody Licorish
*
* Licensed under the MIT License.
*
* test-pngread.c
* png reader test program
*/
#include "../src/auxi.h"
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
struct test_image {
int width;
int height;
unsigned char* bytes;
FILE* outfile;
FILE* alphafile;
};
static int test_image_header
( void* img, long int width, long int height, short bit_depth,
short color_type, short compression, short filter, short interlace);
static void test_image_recv_pixel
( void* img, long int x, long int y, unsigned int red,
unsigned int green, unsigned int blue, unsigned int alpha);
int test_image_header
( void* img_ptr, long int width, long int height, short bit_depth,
short color_type, short compression, short filter, short interlace)
{
struct test_image *img = (struct test_image*)img_ptr;
void* bytes;
fprintf(stderr, "{\"image info\":{\n"
" \"width\": %li,\n"
" \"height\": %li,\n"
" \"bit depth\": %i,\n"
" \"color type\": %i,\n"
" \"compression\": %i,\n"
" \"filter\": %i,\n"
" \"interlace\": %i\n}}\n",
width, height, bit_depth, color_type, compression, filter, interlace
);
if (width > 10000 || height > 10000) return PNGPARTS_API_UNSUPPORTED;
bytes = malloc(width*height * 4);
if (bytes == NULL) return PNGPARTS_API_UNSUPPORTED;
img->width = (int)width;
img->height = (int)height;
img->bytes = (unsigned char*)bytes;
memset(bytes, 55, width*height * 4);
return PNGPARTS_API_OK;
}
void test_image_recv_pixel
( void* img_ptr, long int x, long int y, unsigned int red,
unsigned int green, unsigned int blue, unsigned int alpha)
{
struct test_image *img = (struct test_image*)img_ptr;
unsigned char *const pixel = (&img->bytes[(y*img->width + x)*4]);
/*fprintf(stderr, "pixel for %li %li..\n", x, y);*/
pixel[0] = red;
pixel[1] = green;
pixel[2] = blue;
pixel[3] = alpha;
return;
}
void test_image_put_ppm(struct test_image* img) {
int x, y;
fprintf(img->outfile, "P3\n%i %i\n255\n",
img->width, img->height);
for (y = 0; y < img->height; ++y) {
for (x = 0; x < img->width; ++x) {
unsigned char *const pixel = (&img->bytes[(y*img->width + x) * 4]);
fprintf(img->outfile, "%i %i %i\n",
pixel[0], pixel[1], pixel[2]);
}
}
}
void test_image_put_alphapgm(struct test_image* img) {
int x, y;
fprintf(img->alphafile, "P2\n%i %i\n255\n", img->width, img->height);
for (y = 0; y < img->height; ++y) {
for (x = 0; x < img->width; ++x) {
unsigned char *const pixel = (&img->bytes[(y*img->width + x) * 4]);
fprintf(img->alphafile, "%i\n", pixel[3]);
}
}
return;
}
int main(int argc, char**argv) {
FILE *to_write = NULL;
char const* in_fname = NULL, *out_fname = NULL;
char const* alpha_fname = NULL;
int help_tf = 0;
int result = 0;
struct test_image img = { 0,0,NULL,NULL,NULL };
{
int argi;
for (argi = 1; argi < argc; ++argi) {
if (strcmp(argv[argi], "-?") == 0) {
help_tf = 1;
} else if (strcmp("-a",argv[argi]) == 0){
if (argi+1 < argc){
argi += 1;
alpha_fname = argv[argi];
}
} else if (in_fname == NULL) {
in_fname = argv[argi];
} else if (out_fname == NULL) {
out_fname = argv[argi];
}
}
if (help_tf) {
fprintf(stderr,
"usage: test_pngread [...options...] (infile) (outfile)\n"
" - stdin/stdout\n"
" -? help message\n"
"options:\n"
" -a (file) alpha channel output file\n"
);
return 2;
}
}
/* open */
if (out_fname == NULL) {
fprintf(stderr, "No output file name given.\n");
return 2;
} else if (strcmp(out_fname, "-") == 0) {
to_write = stdout;
} else {
to_write = fopen(out_fname, "wb");
if (to_write == NULL) {
int errval = errno;
fprintf(stderr, "Failed to open '%s'.\n\t%s\n",
out_fname, strerror(errval));
return 1;
}
}
img.outfile = to_write;
/* set image callback */{
struct pngparts_api_image img_api;
img_api.cb_data = &img;
img_api.start_cb = &test_image_header;
img_api.put_cb = &test_image_recv_pixel;
/* parse the PNG stream */
result = pngparts_aux_read_png_8(&img_api, in_fname);
}
/* output to PPM */ {
test_image_put_ppm(&img);
}
/* output the alpha channel */if (alpha_fname != NULL){
FILE *alphafile;
if (to_write != stdout){
fclose(to_write);
to_write = stdout;
}
alphafile = fopen(alpha_fname, "wt");
if (alphafile == NULL){
int errval = errno;
fprintf(stderr, "Failed to open '%s' for alpha channel.\n\t%s\n",
alpha_fname, strerror(errval));
/* close */
free(img.bytes);
if (to_write != stdout) fclose(to_write);
return 1;
} else {
img.alphafile = alphafile;
test_image_put_alphapgm(&img);
fclose(alphafile);
}
}
/* close */
free(img.bytes);
if (to_write != stdout) fclose(to_write);
fflush(NULL);
if (result) {
fprintf(stderr, "\nResult code %i: %s\n",
result, pngparts_api_strerror(result));
}
return result;
}
| [
"[email protected]"
] | |
3767040a2e1cd955e3fe319193724c25eb264c5b | 7aaafbb769c6a6d9f0d10dac4e0a35c54c84fb24 | /libraries/DMXSerial2/src/rdm.h | 1a9aa45b56f0bae5da2ee15a1c2d010073db784c | [
"BSD-3-Clause"
] | permissive | mxTuhin/Arduino | e40dde74f2138386e633782f24941c0f122d985d | 99971441ee1973ffbcb6d7ac99e4eea2eed7dc79 | refs/heads/master | 2023-03-09T09:37:52.602595 | 2021-02-24T21:36:29 | 2021-02-24T21:36:29 | 342,041,987 | 0 | 0 | null | null | null | null | UTF-8 | C | false | false | 52,903 | h | /*****************************************************************/
/* Entertainment Services Technology Association (ESTA) */
/* ANSI E1.20 Remote Device Management (RDM) over DMX512 Networks*/
/*****************************************************************/
/* */
/* RDM.h */
/* */
/*****************************************************************/
/* Appendix A Defines for the RDM Protocol. */
/* Publish date: 3/31/2006 */
/*****************************************************************/
/* Compiled by: Scott M. Blair 8/18/2006 */
/* Updated 10/11/2011: Adding E1.20-2010 and E1.37-1 defines. */
/*****************************************************************/
/* For updates see: http://www.rdmprotocol.org */
/*****************************************************************/
/* Copyright 2006,2011 Litespeed Design */
/*****************************************************************/
/* Permission to use, copy, modify, and distribute this software */
/* is freely granted, provided that this notice is preserved. */
/*****************************************************************/
/* Protocol version. */
#define E120_PROTOCOL_VERSION 0x0100
/* RDM START CODE (Slot 0) */
#define E120_SC_RDM 0xCC
/* RDM Protocol Data Structure ID's (Slot 1) */
#define E120_SC_SUB_MESSAGE 0x01
/* Broadcast Device UID's */
#define E120_BROADCAST_ALL_DEVICES_ID 0xFFFFFFFFFFFF /* (Broadcast all Manufacturers) */
//#define ALL_DEVICES_ID 0xmmmmFFFFFFFF /* (Specific Manufacturer ID 0xmmmm) */
#define E120_SUB_DEVICE_ALL_CALL 0xFFFF
/********************************************************/
/* Table A-1: RDM Command Classes (Slot 20) */
/********************************************************/
#define E120_DISCOVERY_COMMAND 0x10
#define E120_DISCOVERY_COMMAND_RESPONSE 0x11
#define E120_GET_COMMAND 0x20
#define E120_GET_COMMAND_RESPONSE 0x21
#define E120_SET_COMMAND 0x30
#define E120_SET_COMMAND_RESPONSE 0x31
/********************************************************/
/* Table A-2: RDM Response Type (Slot 16) */
/********************************************************/
#define E120_RESPONSE_TYPE_ACK 0x00
#define E120_RESPONSE_TYPE_ACK_TIMER 0x01
#define E120_RESPONSE_TYPE_NACK_REASON 0x02 /* See Table A-17 */
#define E120_RESPONSE_TYPE_ACK_OVERFLOW 0x03 /* Additional Response Data available beyond single response length.*/
/********************************************************/
/* Table A-3: RDM Parameter ID's (Slots 21-22) */
/********************************************************/
/* Category - Network Management */
#define E120_DISC_UNIQUE_BRANCH 0x0001
#define E120_DISC_MUTE 0x0002
#define E120_DISC_UN_MUTE 0x0003
#define E120_PROXIED_DEVICES 0x0010
#define E120_PROXIED_DEVICE_COUNT 0x0011
#define E120_COMMS_STATUS 0x0015
/* Category - Status Collection */
#define E120_QUEUED_MESSAGE 0x0020 /* See Table A-4 */
#define E120_STATUS_MESSAGES 0x0030 /* See Table A-4 */
#define E120_STATUS_ID_DESCRIPTION 0x0031
#define E120_CLEAR_STATUS_ID 0x0032
#define E120_SUB_DEVICE_STATUS_REPORT_THRESHOLD 0x0033 /* See Table A-4 */
/* Category - RDM Information */
#define E120_SUPPORTED_PARAMETERS 0x0050 /* Support required only if supporting Parameters beyond the minimum required set.*/
#define E120_PARAMETER_DESCRIPTION 0x0051 /* Support required for Manufacturer-Specific PIDs exposed in SUPPORTED_PARAMETERS message */
/* Category - Product Information */
#define E120_DEVICE_INFO 0x0060
#define E120_PRODUCT_DETAIL_ID_LIST 0x0070
#define E120_DEVICE_MODEL_DESCRIPTION 0x0080
#define E120_MANUFACTURER_LABEL 0x0081
#define E120_DEVICE_LABEL 0x0082
#define E120_FACTORY_DEFAULTS 0x0090
#define E120_LANGUAGE_CAPABILITIES 0x00A0
#define E120_LANGUAGE 0x00B0
#define E120_SOFTWARE_VERSION_LABEL 0x00C0
#define E120_BOOT_SOFTWARE_VERSION_ID 0x00C1
#define E120_BOOT_SOFTWARE_VERSION_LABEL 0x00C2
/* Category - DMX512 Setup */
#define E120_DMX_PERSONALITY 0x00E0
#define E120_DMX_PERSONALITY_DESCRIPTION 0x00E1
#define E120_DMX_START_ADDRESS 0x00F0 /* Support required if device uses a DMX512 Slot. */
#define E120_SLOT_INFO 0x0120
#define E120_SLOT_DESCRIPTION 0x0121
#define E120_DEFAULT_SLOT_VALUE 0x0122
#define E137_1_DMX_BLOCK_ADDRESS 0x0140 /* Defined in ANSI E1.37-1 document */
#define E137_1_DMX_FAIL_MODE 0x0141 /* Defined in ANSI E1.37-1 document */
#define E137_1_DMX_STARTUP_MODE 0x0142 /* Defined in ANSI E1.37-1 document */
/* Category - Sensors */
#define E120_SENSOR_DEFINITION 0x0200
#define E120_SENSOR_VALUE 0x0201
#define E120_RECORD_SENSORS 0x0202
/* Category - Dimmer Settings */
#define E137_1_DIMMER_INFO 0x0340
#define E137_1_MINIMUM_LEVEL 0x0341
#define E137_1_MAXIMUM_LEVEL 0x0342
#define E137_1_CURVE 0x0343
#define E137_1_CURVE_DESCRIPTION 0x0344 /* Support required if CURVE is supported */
#define E137_1_OUTPUT_RESPONSE_TIME 0x0345
#define E137_1_OUTPUT_RESPONSE_TIME_DESCRIPTION 0x0346 /* Support required if OUTPUT_RESPONSE_TIME is supported */
#define E137_1_MODULATION_FREQUENCY 0x0347
#define E137_1_MODULATION_FREQUENCY_DESCRIPTION 0x0348 /* Support required if MODULATION_FREQUENCY is supported */
/* Category - Power/Lamp Settings */
#define E120_DEVICE_HOURS 0x0400
#define E120_LAMP_HOURS 0x0401
#define E120_LAMP_STRIKES 0x0402
#define E120_LAMP_STATE 0x0403 /* See Table A-8 */
#define E120_LAMP_ON_MODE 0x0404 /* See Table A-9 */
#define E120_DEVICE_POWER_CYCLES 0x0405
#define E137_1_BURN_IN 0x0440 /* Defined in ANSI E1.37-1 */
/* Category - Display Settings */
#define E120_DISPLAY_INVERT 0x0500
#define E120_DISPLAY_LEVEL 0x0501
/* Category - Configuration */
#define E120_PAN_INVERT 0x0600
#define E120_TILT_INVERT 0x0601
#define E120_PAN_TILT_SWAP 0x0602
#define E120_REAL_TIME_CLOCK 0x0603
#define E137_1_LOCK_PIN 0x0640 /* Defined in ANSI E1.37-1 */
#define E137_1_LOCK_STATE 0x0641 /* Defined in ANSI E1.37-1 */
#define E137_1_LOCK_STATE_DESCRIPTION 0x0642 /* Support required if MODULATION_FREQUENCY is supported */
/* Category - Control */
#define E120_IDENTIFY_DEVICE 0x1000
#define E120_RESET_DEVICE 0x1001
#define E120_POWER_STATE 0x1010 /* See Table A-11 */
#define E120_PERFORM_SELFTEST 0x1020 /* See Table A-10 */
#define E120_SELF_TEST_DESCRIPTION 0x1021
#define E120_CAPTURE_PRESET 0x1030
#define E120_PRESET_PLAYBACK 0x1031 /* See Table A-7 */
#define E137_1_IDENTIFY_MODE 0x1040 /* Defined in ANSI E1.37-1 */
#define E137_1_PRESET_INFO 0x1041 /* Defined in ANSI E1.37-1 */
#define E137_1_PRESET_STATUS 0x1042 /* Defined in ANSI E1.37-1 */
#define E137_1_PRESET_MERGEMODE 0x1043 /* See E1.37-1 Table A-3 */
#define E137_1_POWER_ON_SELF_TEST 0x1044 /* Defined in ANSI E1.37-1 */
/* ESTA Reserved Future RDM Development 0x7FE0-
0x7FFF
Manufacturer-Specific PIDs 0x8000-
0xFFDF
ESTA Reserved Future RDM Development
0xFFE0-
0xFFFF
*/
/*****************************************************************/
/* Discovery Mute/Un-Mute Messages Control Field. See Table 7-3. */
/*****************************************************************/
#define E120_CONTROL_PROXIED_DEVICE 0x0008
#define E120_CONTROL_BOOT_LOADER 0x0004
#define E120_CONTROL_SUB_DEVICE 0x0002
#define E120_CONTROL_MANAGED_PROXY 0x0001
/********************************************************/
/* Table A-4: Status Type Defines */
/********************************************************/
#define E120_STATUS_NONE 0x00 /* Not allowed for use with GET: QUEUED_MESSAGE */
#define E120_STATUS_GET_LAST_MESSAGE 0x01
#define E120_STATUS_ADVISORY 0x02
#define E120_STATUS_WARNING 0x03
#define E120_STATUS_ERROR 0x04
#define E120_STATUS_ADVISORY_CLEARED 0x12 /* Added in E1.20-2010 version */
#define E120_STATUS_WARNING_CLEARED 0x13 /* Added in E1.20-2010 version */
#define E120_STATUS_ERROR_CLEARED 0x14 /* Added in E1.20-2010 version */
/********************************************************/
/* Table A-5: Product Category Defines */
/********************************************************/
#define E120_PRODUCT_CATEGORY_NOT_DECLARED 0x0000
/* Fixtures - intended as source of illumination See Note 1 */
#define E120_PRODUCT_CATEGORY_FIXTURE 0x0100 /* No Fine Category declared */
#define E120_PRODUCT_CATEGORY_FIXTURE_FIXED 0x0101 /* No pan / tilt / focus style functions */
#define E120_PRODUCT_CATEGORY_FIXTURE_MOVING_YOKE 0x0102
#define E120_PRODUCT_CATEGORY_FIXTURE_MOVING_MIRROR 0x0103
#define E120_PRODUCT_CATEGORY_FIXTURE_OTHER 0x01FF /* For example, focus but no pan/tilt. */
/* Fixture Accessories - add-ons to fixtures or projectors */
#define E120_PRODUCT_CATEGORY_FIXTURE_ACCESSORY 0x0200 /* No Fine Category declared. */
#define E120_PRODUCT_CATEGORY_FIXTURE_ACCESSORY_COLOR 0x0201 /* Scrollers / Color Changers */
#define E120_PRODUCT_CATEGORY_FIXTURE_ACCESSORY_YOKE 0x0202 /* Yoke add-on */
#define E120_PRODUCT_CATEGORY_FIXTURE_ACCESSORY_MIRROR 0x0203 /* Moving mirror add-on */
#define E120_PRODUCT_CATEGORY_FIXTURE_ACCESSORY_EFFECT 0x0204 /* Effects Discs */
#define E120_PRODUCT_CATEGORY_FIXTURE_ACCESSORY_BEAM 0x0205 /* Gobo Rotators /Iris / Shutters / Dousers/ Beam modifiers. */
#define E120_PRODUCT_CATEGORY_FIXTURE_ACCESSORY_OTHER 0x02FF
/* Projectors - light source capable of producing realistic images from another media i.e Video / Slide / Oil Wheel / Film */
#define E120_PRODUCT_CATEGORY_PROJECTOR 0x0300 /* No Fine Category declared. */
#define E120_PRODUCT_CATEGORY_PROJECTOR_FIXED 0x0301 /* No pan / tilt functions. */
#define E120_PRODUCT_CATEGORY_PROJECTOR_MOVING_YOKE 0x0302
#define E120_PRODUCT_CATEGORY_PROJECTOR_MOVING_MIRROR 0x0303
#define E120_PRODUCT_CATEGORY_PROJECTOR_OTHER 0x03FF
/* Atmospheric Effect - earth/wind/fire */
#define E120_PRODUCT_CATEGORY_ATMOSPHERIC 0x0400 /* No Fine Category declared. */
#define E120_PRODUCT_CATEGORY_ATMOSPHERIC_EFFECT 0x0401 /* Fogger / Hazer / Flame, etc. */
#define E120_PRODUCT_CATEGORY_ATMOSPHERIC_PYRO 0x0402 /* See Note 2. */
#define E120_PRODUCT_CATEGORY_ATMOSPHERIC_OTHER 0x04FF
/* Intensity Control (specifically Dimming equipment) */
#define E120_PRODUCT_CATEGORY_DIMMER 0x0500 /* No Fine Category declared. */
#define E120_PRODUCT_CATEGORY_DIMMER_AC_INCANDESCENT 0x0501 /* AC > 50VAC */
#define E120_PRODUCT_CATEGORY_DIMMER_AC_FLUORESCENT 0x0502
#define E120_PRODUCT_CATEGORY_DIMMER_AC_COLDCATHODE 0x0503 /* High Voltage outputs such as Neon or other cold cathode. */
#define E120_PRODUCT_CATEGORY_DIMMER_AC_NONDIM 0x0504 /* Non-Dim module in dimmer rack. */
#define E120_PRODUCT_CATEGORY_DIMMER_AC_ELV 0x0505 /* AC <= 50V such as 12/24V AC Low voltage lamps. */
#define E120_PRODUCT_CATEGORY_DIMMER_AC_OTHER 0x0506
#define E120_PRODUCT_CATEGORY_DIMMER_DC_LEVEL 0x0507 /* Variable DC level output. */
#define E120_PRODUCT_CATEGORY_DIMMER_DC_PWM 0x0508 /* Chopped (PWM) output. */
#define E120_PRODUCT_CATEGORY_DIMMER_CS_LED 0x0509 /* Specialized LED dimmer. */
#define E120_PRODUCT_CATEGORY_DIMMER_OTHER 0x05FF
/* Power Control (other than Dimming equipment) */
#define E120_PRODUCT_CATEGORY_POWER 0x0600 /* No Fine Category declared. */
#define E120_PRODUCT_CATEGORY_POWER_CONTROL 0x0601 /* Contactor racks, other forms of Power Controllers. */
#define E120_PRODUCT_CATEGORY_POWER_SOURCE 0x0602 /* Generators */
#define E120_PRODUCT_CATEGORY_POWER_OTHER 0x06FF
/* Scenic Drive - including motorized effects unrelated to light source. */
#define E120_PRODUCT_CATEGORY_SCENIC 0x0700 /* No Fine Category declared */
#define E120_PRODUCT_CATEGORY_SCENIC_DRIVE 0x0701 /* Rotators / Kabuki drops, etc. See Note 2. */
#define E120_PRODUCT_CATEGORY_SCENIC_OTHER 0x07FF
/* DMX Infrastructure, conversion and interfaces */
#define E120_PRODUCT_CATEGORY_DATA 0x0800 /* No Fine Category declared. */
#define E120_PRODUCT_CATEGORY_DATA_DISTRIBUTION 0x0801 /* Splitters/repeaters/Ethernet products used to distribute DMX*/
#define E120_PRODUCT_CATEGORY_DATA_CONVERSION 0x0802 /* Protocol Conversion analog decoders. */
#define E120_PRODUCT_CATEGORY_DATA_OTHER 0x08FF
/* Audio-Visual Equipment */
#define E120_PRODUCT_CATEGORY_AV 0x0900 /* No Fine Category declared. */
#define E120_PRODUCT_CATEGORY_AV_AUDIO 0x0901 /* Audio controller or device. */
#define E120_PRODUCT_CATEGORY_AV_VIDEO 0x0902 /* Video controller or display device. */
#define E120_PRODUCT_CATEGORY_AV_OTHER 0x09FF
/* Parameter Monitoring Equipment See Note 3. */
#define E120_PRODUCT_CATEGORY_MONITOR 0x0A00 /* No Fine Category declared. */
#define E120_PRODUCT_CATEGORY_MONITOR_ACLINEPOWER 0x0A01 /* Product that monitors AC line voltage, current or power. */
#define E120_PRODUCT_CATEGORY_MONITOR_DCPOWER 0x0A02 /* Product that monitors DC line voltage, current or power. */
#define E120_PRODUCT_CATEGORY_MONITOR_ENVIRONMENTAL 0x0A03 /* Temperature or other environmental parameter. */
#define E120_PRODUCT_CATEGORY_MONITOR_OTHER 0x0AFF
/* Controllers, Backup devices */
#define E120_PRODUCT_CATEGORY_CONTROL 0x7000 /* No Fine Category declared. */
#define E120_PRODUCT_CATEGORY_CONTROL_CONTROLLER 0x7001
#define E120_PRODUCT_CATEGORY_CONTROL_BACKUPDEVICE 0x7002
#define E120_PRODUCT_CATEGORY_CONTROL_OTHER 0x70FF
/* Test Equipment */
#define E120_PRODUCT_CATEGORY_TEST 0x7100 /* No Fine Category declared. */
#define E120_PRODUCT_CATEGORY_TEST_EQUIPMENT 0x7101
#define E120_PRODUCT_CATEGORY_TEST_EQUIPMENT_OTHER 0x71FF
/* Miscellaneous */
#define E120_PRODUCT_CATEGORY_OTHER 0x7FFF /* For devices that aren't described within this table. */
/* Manufacturer Specific Categories 0x8000 -
0xDFFF */
/********************************************************/
/* Table A-6: Product Detail Defines */
/********************************************************/
#define E120_PRODUCT_DETAIL_NOT DECLARED 0x0000
/* Generally applied to fixtures */
#define E120_PRODUCT_DETAIL_ARC 0x0001
#define E120_PRODUCT_DETAIL_METAL_HALIDE 0x0002
#define E120_PRODUCT_DETAIL_INCANDESCENT 0x0003
#define E120_PRODUCT_DETAIL_LED 0x0004
#define E120_PRODUCT_DETAIL_FLUORESCENT 0x0005
#define E120_PRODUCT_DETAIL_COLDCATHODE 0x0006 /*includes Neon/Argon */
#define E120_PRODUCT_DETAIL_ELECTROLUMINESCENT 0x0007
#define E120_PRODUCT_DETAIL_LASER 0x0008
#define E120_PRODUCT_DETAIL_FLASHTUBE 0x0009 /* Strobes or other flashtubes */
/* Generally applied to fixture accessories */
#define E120_PRODUCT_DETAIL_COLORSCROLLER 0x0100
#define E120_PRODUCT_DETAIL_COLORWHEEL 0x0101
#define E120_PRODUCT_DETAIL_COLORCHANGE 0x0102 /* Semaphore or other type */
#define E120_PRODUCT_DETAIL_IRIS_DOUSER 0x0103
#define E120_PRODUCT_DETAIL_DIMMING_SHUTTER 0x0104
#define E120_PRODUCT_DETAIL_PROFILE_SHUTTER 0x0105 /* hard-edge beam masking */
#define E120_PRODUCT_DETAIL_BARNDOOR_SHUTTER 0x0106 /* soft-edge beam masking */
#define E120_PRODUCT_DETAIL_EFFECTS_DISC 0x0107
#define E120_PRODUCT_DETAIL_GOBO_ROTATOR 0x0108
/* Generally applied to Projectors */
#define E120_PRODUCT_DETAIL_VIDEO 0x0200
#define E120_PRODUCT_DETAIL_SLIDE 0x0201
#define E120_PRODUCT_DETAIL_FILM 0x0202
#define E120_PRODUCT_DETAIL_OILWHEEL 0x0203
#define E120_PRODUCT_DETAIL_LCDGATE 0x0204
/* Generally applied to Atmospheric Effects */
#define E120_PRODUCT_DETAIL_FOGGER_GLYCOL 0x0300 /* Glycol/Glycerin hazer */
#define E120_PRODUCT_DETAIL_FOGGER_MINERALOIL 0x0301 /* White Mineral oil hazer */
#define E120_PRODUCT_DETAIL_FOGGER_WATER 0x0302 /* Water hazer */
#define E120_PRODUCT_DETAIL_C02 0x0303 /* Dry Ice/Carbon Dioxide based */
#define E120_PRODUCT_DETAIL_LN2 0x0304 /* Nitrogen based */
#define E120_PRODUCT_DETAIL_BUBBLE 0x0305 /* including foam */
#define E120_PRODUCT_DETAIL_FLAME_PROPANE 0x0306
#define E120_PRODUCT_DETAIL_FLAME_OTHER 0x0307
#define E120_PRODUCT_DETAIL_OLEFACTORY_STIMULATOR 0x0308 /* Scents */
#define E120_PRODUCT_DETAIL_SNOW 0x0309
#define E120_PRODUCT_DETAIL_WATER_JET 0x030A /* Fountain controls etc */
#define E120_PRODUCT_DETAIL_WIND 0x030B /* Air Mover */
#define E120_PRODUCT_DETAIL_CONFETTI 0x030C
#define E120_PRODUCT_DETAIL_HAZARD 0x030D /* Any form of pyrotechnic control or device. */
/* Generally applied to Dimmers/Power controllers See Note 1 */
#define E120_PRODUCT_DETAIL_PHASE_CONTROL 0x0400
#define E120_PRODUCT_DETAIL_REVERSE_PHASE_CONTROL 0x0401 /* includes FET/IGBT */
#define E120_PRODUCT_DETAIL_SINE 0x0402
#define E120_PRODUCT_DETAIL_PWM 0x0403
#define E120_PRODUCT_DETAIL_DC 0x0404 /* Variable voltage */
#define E120_PRODUCT_DETAIL_HFBALLAST 0x0405 /* for Fluorescent */
#define E120_PRODUCT_DETAIL_HFHV_NEONBALLAST 0x0406 /* for Neon/Argon and other coldcathode. */
#define E120_PRODUCT_DETAIL_HFHV_EL 0x0407 /* for Electroluminscent */
#define E120_PRODUCT_DETAIL_MHR_BALLAST 0x0408 /* for Metal Halide */
#define E120_PRODUCT_DETAIL_BITANGLE_MODULATION 0x0409
#define E120_PRODUCT_DETAIL_FREQUENCY_MODULATION 0x040A
#define E120_PRODUCT_DETAIL_HIGHFREQUENCY_12V 0x040B /* as commonly used with MR16 lamps */
#define E120_PRODUCT_DETAIL_RELAY_MECHANICAL 0x040C /* See Note 1 */
#define E120_PRODUCT_DETAIL_RELAY_ELECTRONIC 0x040D /* See Note 1, Note 2 */
#define E120_PRODUCT_DETAIL_SWITCH_ELECTRONIC 0x040E /* See Note 1, Note 2 */
#define E120_PRODUCT_DETAIL_CONTACTOR 0x040F /* See Note 1 */
/* Generally applied to Scenic drive */
#define E120_PRODUCT_DETAIL_MIRRORBALL_ROTATOR 0x0500
#define E120_PRODUCT_DETAIL_OTHER_ROTATOR 0x0501 /* includes turntables */
#define E120_PRODUCT_DETAIL_KABUKI_DROP 0x0502
#define E120_PRODUCT_DETAIL_CURTAIN 0x0503 /* flown or traveller */
#define E120_PRODUCT_DETAIL_LINESET 0x0504
#define E120_PRODUCT_DETAIL_MOTOR_CONTROL 0x0505
#define E120_PRODUCT_DETAIL_DAMPER_CONTROL 0x0506 /* HVAC Damper */
/* Generally applied to Data Distribution */
#define E120_PRODUCT_DETAIL_SPLITTER 0x0600 /* Includes buffers/repeaters */
#define E120_PRODUCT_DETAIL_ETHERNET_NODE 0x0601 /* DMX512 to/from Ethernet */
#define E120_PRODUCT_DETAIL_MERGE 0x0602 /* DMX512 combiner */
#define E120_PRODUCT_DETAIL_DATAPATCH 0x0603 /* Electronic Datalink Patch */
#define E120_PRODUCT_DETAIL_WIRELESS_LINK 0x0604 /* radio/infrared */
/* Generally applied to Data Conversion and Interfaces */
#define E120_PRODUCT_DETAIL_PROTOCOL_CONVERTER 0x0701 /* D54/AMX192/Non DMX serial links, etc to/from DMX512 */
#define E120_PRODUCT_DETAIL_ANALOG_DEMULTIPLEX 0x0702 /* DMX to DC voltage */
#define E120_PRODUCT_DETAIL_ANALOG_MULTIPLEX 0x0703 /* DC Voltage to DMX */
#define E120_PRODUCT_DETAIL_SWITCH_PANEL 0x0704 /* Pushbuttons to DMX or polled using RDM */
/* Generally applied to Audio or Video (AV) devices */
#define E120_PRODUCT_DETAIL_ROUTER 0x0800 /* Switching device */
#define E120_PRODUCT_DETAIL_FADER 0x0801 /* Single channel */
#define E120_PRODUCT_DETAIL_MIXER 0x0802 /* Multi-channel */
/* Generally applied to Controllers, Backup devices and Test Equipment */
#define E120_PRODUCT_DETAIL_CHANGEOVER_MANUAL 0x0900 /* requires manual intervention to assume control of DMX line */
#define E120_PRODUCT_DETAIL_CHANGEOVER_AUTO 0x0901 /* may automatically assume control of DMX line */
#define E120_PRODUCT_DETAIL_TEST 0x0902 /* test equipment */
/* Could be applied to any category */
#define E120_PRODUCT_DETAIL_GFI_RCD 0x0A00 /* device includes GFI/RCD trip */
#define E120_PRODUCT_DETAIL_BATTERY 0x0A01 /* device is battery operated */
#define E120_PRODUCT_DETAIL_CONTROLLABLE_BREAKER 0x0A02
#define E120_PRODUCT_DETAIL_OTHER 0x7FFF /* for use where the Manufacturer believes that none of the
defined details apply. */
/* Manufacturer Specific Types 0x8000-
0xDFFF */
/* Note 1: Products intended for switching 50V AC / 120V DC or greater should be declared with a
Product Category of PRODUCT_CATEGORY_POWER_CONTROL.
Products only suitable for extra low voltage switching (typically up to 50VAC / 30VDC) at currents
less than 1 ampere should be declared with a Product Category of PRODUCT_CATEGORY_DATA_CONVERSION.
Please refer to GET: DEVICE_INFO and Table A-5 for an explanation of Product Category declaration.
Note 2: Products with TTL, MOSFET or Open Collector Transistor Outputs or similar non-isolated electronic
outputs should be declared as PRODUCT_DETAIL_SWITCH_ELECTRONIC. Use of PRODUCT_DETAIL_RELAY_ELECTRONIC
shall be restricted to devices whereby the switched circuits are electrically isolated from the control signals. */
/********************************************************/
/* Table A-7: Preset Playback Defines */
/********************************************************/
#define E120_PRESET_PLAYBACK_OFF 0x0000 /* Returns to Normal DMX512 Input */
#define E120_PRESET_PLAYBACK_ALL 0xFFFF /* Plays Scenes in Sequence if supported. */
/* E120_PRESET_PLAYBACK_SCENE 0x0001-
0xFFFE Plays individual Scene # */
/********************************************************/
/* Table A-8: Lamp State Defines */
/********************************************************/
#define E120_LAMP_OFF 0x00 /* No demonstrable light output */
#define E120_LAMP_ON 0x01
#define E120_LAMP_STRIKE 0x02 /* Arc-Lamp ignite */
#define E120_LAMP_STANDBY 0x03 /* Arc-Lamp Reduced Power Mode */
#define E120_LAMP_NOT_PRESENT 0x04 /* Lamp not installed */
#define E120_LAMP_ERROR 0x7F
/* Manufacturer-Specific States 0x80-
0xDF */
/********************************************************/
/* Table A-9: Lamp On Mode Defines */
/********************************************************/
#define E120_LAMP_ON_MODE_OFF 0x00 /* Lamp Stays off until directly instructed to Strike. */
#define E120_LAMP_ON_MODE_DMX 0x01 /* Lamp Strikes upon receiving a DMX512 signal. */
#define E120_LAMP_ON_MODE_ON 0x02 /* Lamp Strikes automatically at Power-up. */
#define E120_LAMP_ON_MODE_AFTER_CAL 0x03 /* Lamp Strikes after Calibration or Homing procedure. */
/* Manufacturer-Specific Modes 0x80-
0xDF */
/********************************************************/
/* Table A-10: Self Test Defines */
/********************************************************/
#define E120_SELF_TEST_OFF 0x00 /* Turns Self Tests Off */
/* Manufacturer Tests 0x01-
0xFE Various Manufacturer Self Tests */
#define E120_SELF_TEST_ALL 0xFF /* Self Test All, if applicable */
/********************************************************/
/* Table A-11: Power State Defines */
/********************************************************/
#define E120_POWER_STATE_FULL_OFF 0x00 /* Completely disengages power to device. Device can no longer respond. */
#define E120_POWER_STATE_SHUTDOWN 0x01 /* Reduced power mode, may require device reset to return to
normal operation. Device still responds to messages. */
#define E120_POWER_STATE_STANDBY 0x02 /* Reduced power mode. Device can return to NORMAL without a
reset. Device still responds to messages. */
#define E120_POWER_STATE_NORMAL 0xFF /* Normal Operating Mode. */
/********************************************************/
/* Table A-12: Sensor Type Defines */
/********************************************************/
#define E120_SENS_TEMPERATURE 0x00
#define E120_SENS_VOLTAGE 0x01
#define E120_SENS_CURRENT 0x02
#define E120_SENS_FREQUENCY 0x03
#define E120_SENS_RESISTANCE 0x04 /* Eg: Cable resistance */
#define E120_SENS_POWER 0x05
#define E120_SENS_MASS 0x06 /* Eg: Truss load Cell */
#define E120_SENS_LENGTH 0x07
#define E120_SENS_AREA 0x08
#define E120_SENS_VOLUME 0x09 /* Eg: Smoke Fluid */
#define E120_SENS_DENSITY 0x0A
#define E120_SENS_VELOCITY 0x0B
#define E120_SENS_ACCELERATION 0x0C
#define E120_SENS_FORCE 0x0D
#define E120_SENS_ENERGY 0x0E
#define E120_SENS_PRESSURE 0x0F
#define E120_SENS_TIME 0x10
#define E120_SENS_ANGLE 0x11
#define E120_SENS_POSITION_X 0x12 /* E.g.: Lamp position on Truss */
#define E120_SENS_POSITION_Y 0x13
#define E120_SENS_POSITION_Z 0x14
#define E120_SENS_ANGULAR_VELOCITY 0x15 /* E.g.: Wind speed */
#define E120_SENS_LUMINOUS_INTENSITY 0x16
#define E120_SENS_LUMINOUS_FLUX 0x17
#define E120_SENS_ILLUMINANCE 0x18
#define E120_SENS_CHROMINANCE_RED 0x19
#define E120_SENS_CHROMINANCE_GREEN 0x1A
#define E120_SENS_CHROMINANCE_BLUE 0x1B
#define E120_SENS_CONTACTS 0x1C /* E.g.: Switch inputs. */
#define E120_SENS_MEMORY 0x1D /* E.g.: ROM Size */
#define E120_SENS_ITEMS 0x1E /* E.g.: Scroller gel frames. */
#define E120_SENS_HUMIDITY 0x1F
#define E120_SENS_COUNTER_16BIT 0x20
#define E120_SENS_OTHER 0x7F
/* Manufacturer-Specific Sensors 0x80-
0xFF */
/********************************************************/
/* Table A-13: Sensor Unit Defines */
/********************************************************/
#define E120_UNITS_NONE 0x00 /* CONTACTS */
#define E120_UNITS_CENTIGRADE 0x01 /* TEMPERATURE */
#define E120_UNITS_VOLTS_DC 0x02 /* VOLTAGE */
#define E120_UNITS_VOLTS_AC_PEAK 0x03 /* VOLTAGE */
#define E120_UNITS_VOLTS_AC_RMS 0x04 /* VOLTAGE */
#define E120_UNITS_AMPERE_DC 0x05 /* CURRENT */
#define E120_UNITS_AMPERE_AC_PEAK 0x06 /* CURRENT */
#define E120_UNITS_AMPERE_AC_RMS 0x07 /* CURRENT */
#define E120_UNITS_HERTZ 0x08 /* FREQUENCY / ANGULAR_VELOCITY */
#define E120_UNITS_OHM 0x09 /* RESISTANCE */
#define E120_UNITS_WATT 0x0A /* POWER */
#define E120_UNITS_KILOGRAM 0x0B /* MASS */
#define E120_UNITS_METERS 0x0C /* LENGTH / POSITION */
#define E120_UNITS_METERS_SQUARED 0x0D /* AREA */
#define E120_UNITS_METERS_CUBED 0x0E /* VOLUME */
#define E120_UNITS_KILOGRAMMES_PER_METER_CUBED 0x0F /* DENSITY */
#define E120_UNITS_METERS_PER_SECOND 0x10 /* VELOCITY */
#define E120_UNITS_METERS_PER_SECOND_SQUARED 0x11 /* ACCELERATION */
#define E120_UNITS_NEWTON 0x12 /* FORCE */
#define E120_UNITS_JOULE 0x13 /* ENERGY */
#define E120_UNITS_PASCAL 0x14 /* PRESSURE */
#define E120_UNITS_SECOND 0x15 /* TIME */
#define E120_UNITS_DEGREE 0x16 /* ANGLE */
#define E120_UNITS_STERADIAN 0x17 /* ANGLE */
#define E120_UNITS_CANDELA 0x18 /* LUMINOUS_INTENSITY */
#define E120_UNITS_LUMEN 0x19 /* LUMINOUS_FLUX */
#define E120_UNITS_LUX 0x1A /* ILLUMINANCE */
#define E120_UNITS_IRE 0x1B /* CHROMINANCE */
#define E120_UNITS_BYTE 0x1C /* MEMORY */
/* Manufacturer-Specific Units 0x80-
0xFF */
/********************************************************/
/* Table A-14: Sensor Unit Prefix Defines */
/********************************************************/
#define E120_PREFIX_NONE 0x00 /* Multiply by 1 */
#define E120_PREFIX_DECI 0x01 /* Multiply by 10-1 */
#define E120_PREFIX_CENTI 0x02 /* Multiply by 10-2 */
#define E120_PREFIX_MILLI 0x03 /* Multiply by 10-3 */
#define E120_PREFIX_MICRO 0x04 /* Multiply by 10-6 */
#define E120_PREFIX_NANO 0x05 /* Multiply by 10-9 */
#define E120_PREFIX_PICO 0x06 /* Multiply by 10-12 */
#define E120_PREFIX_FEMTO 0x07 /* Multiply by 10-15 */
#define E120_PREFIX_ATTO 0x08 /* Multiply by 10-18 */
#define E120_PREFIX_ZEPTO 0x09 /* Multiply by 10-21 */
#define E120_PREFIX_YOCTO 0x0A /* Multiply by 10-24 */
#define E120_PREFIX_DECA 0x11 /* Multiply by 10+1 */
#define E120_PREFIX_HECTO 0x12 /* Multiply by 10+2 */
#define E120_PREFIX_KILO 0x13 /* Multiply by 10+3 */
#define E120_PREFIX_MEGA 0x14 /* Multiply by 10+6 */
#define E120_PREFIX_GIGA 0x15 /* Multiply by 10+9 */
#define E120_PREFIX_TERA 0x16 /* Multiply by 10+12 */
#define E120_PREFIX_PETA 0x17 /* Multiply by 10+15 */
#define E120_PREFIX_EXA 0x18 /* Multiply by 10+18 */
#define E120_PREFIX_ZETTA 0x19 /* Multiply by 10+21 */
#define E120_PREFIX_YOTTA 0x1A /* Multiply by 10+24 */
/********************************************************/
/* Table A-15: Data Type Defines */
/********************************************************/
#define E120_DS_NOT_DEFINED 0x00 /* Data type is not defined */
#define E120_DS_BIT_FIELD 0x01 /* Data is bit packed */
#define E120_DS_ASCII 0x02 /* Data is a string */
#define E120_DS_UNSIGNED_BYTE 0x03 /* Data is an array of unsigned bytes */
#define E120_DS_SIGNED_BYTE 0x04 /* Data is an array of signed bytes */
#define E120_DS_UNSIGNED_WORD 0x05 /* Data is an array of unsigned 16-bit words */
#define E120_DS_SIGNED_WORD 0x06 /* Data is an array of signed 16-bit words */
#define E120_DS_UNSIGNED_DWORD 0x07 /* Data is an array of unsigned 32-bit words */
#define E120_DS_SIGNED_DWORD 0x08 /* Data is an array of signed 32-bit words */
/* Manufacturer-Specific Data Types 0x80- */
/* 0xDF */
/********************************************************/
/* Table A-16: Parameter Desc. Command Class Defines */
/********************************************************/
#define E120_CC_GET 0x01 /* PID supports GET only */
#define E120_CC_SET 0x02 /* PID supports SET only */
#define E120_CC_GET_SET 0x03 /* PID supports GET & SET */
/********************************************************/
/* Table A-17: Response NACK Reason Code Defines */
/********************************************************/
#define E120_NR_UNKNOWN_PID 0x0000 /* The responder cannot comply with request because the message
is not implemented in responder. */
#define E120_NR_FORMAT_ERROR 0x0001 /* The responder cannot interpret request as controller data
was not formatted correctly. */
#define E120_NR_HARDWARE_FAULT 0x0002 /* The responder cannot comply due to an internal hardware fault*/
#define E120_NR_PROXY_REJECT 0x0003 /* Proxy is not the RDM line master and cannot comply with message.*/
#define E120_NR_WRITE_PROTECT 0x0004 /* SET Command normally allowed but being blocked currently. */
#define E120_NR_UNSUPPORTED_COMMAND_CLASS 0x0005 /* Not valid for Command Class attempted. May be used where
GET allowed but SET is not supported. */
#define E120_NR_DATA_OUT_OF_RANGE 0x0006 /* Value for given Parameter out of allowable range or
not supported. */
#define E120_NR_BUFFER_FULL 0x0007 /* Buffer or Queue space currently has no free space to store data. */
#define E120_NR_PACKET_SIZE_UNSUPPORTED 0x0008 /* Incoming message exceeds buffer capacity. */
#define E120_NR_SUB_DEVICE_OUT_OF_RANGE 0x0009 /* Sub-Device is out of range or unknown. */
#define E120_NR_PROXY_BUFFER_FULL 0x000A /* Proxy buffer is full and can not store any more Queued */
/* Message or Status Message responses. */
/********************************************************************************************************************************/
/********************************************************************************************************************************/
/* ANSI E1.37-1 DEFINES */
/********************************************************************************************************************************/
/********************************************************************************************************************************/
/********************************************************/
/* E1.37-1 Table A-2: Preset Programmed Defines */
/********************************************************/
#define E137_1_PRESET_NOT_PROGRAMMED 0x00 /* Preset Scene not programmed. */
#define E137_1_PRESET_PROGRAMMED 0x01 /* Preset Scene programmed. */
#define E137_1_PRESET_PROGRAMMED_READ_ONLY 0x02 /* Preset Scene read-only, factory programmed. */
/********************************************************/
/* E1.37-1 Table A-3: Merge Mode Defines */
/********************************************************/
#define E137_1_MERGEMODE_DEFAULT 0x00 /* Preset overrides DMX512 default behavior as defined in */
/* E1.20 PRESET_PLAYBACK */
#define E137_1_MERGEMODE_HTP 0x01 /* Highest Takes Precedence on slot by slot basis */
#define E137_1_MERGEMODE_LTP 0x02 /* Latest Takes Precedence from Preset or DMX512 on slot by slot */
#define E137_1_MERGEMODE_DMX_ONLY 0x03 /* DMX512 only, Preset ignored */
#define E137_1_MERGEMODE_OTHER 0xFF /* Other (undefined) merge mode */
| [
"[email protected]"
] | |
8d22f9ebcd34c4889b228c169762c6c13c11c745 | 9be6d5538813e6ed3ed39d461389152f98412d62 | /ECU/control_client/src/custom_command.c | 3c0896f982ba0e4ba0ee481be2f1edc4c459517c | [] | no_license | tomyqg/STM32_RTT_F107 | 72144b18d41bdce572ff0f068e2fbd6aa51a3333 | 627dbf278ab182f363e4f6b321714e57fc0f6db7 | refs/heads/master | 2021-09-01T09:13:26.578838 | 2017-12-26T06:20:27 | 2017-12-26T06:20:27 | 115,422,343 | 1 | 0 | null | 2017-12-26T12:58:17 | 2017-12-26T12:58:17 | null | UTF-8 | C | false | false | 2,073 | c | /*****************************************************************************/
/* File : custom_command.c */
/*****************************************************************************/
/* History: */
/*****************************************************************************/
/* Date * Author * Changes */
/*****************************************************************************/
/* 2017-04-07 * Shengfeng Dong * Creation of the file */
/* * * */
/*****************************************************************************/
/*****************************************************************************/
/* Include Files */
/*****************************************************************************/
#include <stdlib.h>
#include <string.h>
#include "remote_control_protocol.h"
#include "debug.h"
#include "mycommand.h"
/*****************************************************************************/
/* Function Implementations */
/*****************************************************************************/
/* 【A108】EMA向ECU发送自定义命令 */
int custom_command(const char *recvbuffer, char *sendbuffer)
{
int ack_flag = SUCCESS;
char command[256] = {'\0'};
char timestamp[15] = {'\0'};
//时间戳
strncpy(timestamp, &recvbuffer[30], 14);
//自定义命令
if(msg_get_one_section(command, &recvbuffer[47]) <= 0){
ack_flag = FORMAT_ERROR;
}
else{
//结束程序命令
if(!strncmp(command, "quit", 4)){
printmsg(ECU_DBG_CONTROL_CLIENT,"Ready to quit");
msg_ACK(sendbuffer, "A108", timestamp, ack_flag);
return -1;
}
//执行自定义命令
ack_flag = mysystem(command);
}
msg_ACK(sendbuffer, "A108", timestamp, ack_flag);
return 0;
}
| [
"[email protected]"
] | |
6506ba928ce812f6c393cf9e1ebea38b6c430d45 | fd75a571284faeb6e590b2e72eecf2943571fa9f | /project-conf.h | 4b48f1bb546fc49f597353a969bf81f4e37be57b | [] | no_license | RManPT/IIoTSE | 2a13caf4feb20218a533cbf6bcae468b20587644 | 85bf9642b2efdc2972e8e242b65b155d3c25c638 | refs/heads/master | 2021-05-03T05:20:09.534988 | 2018-02-17T18:24:06 | 2018-02-17T18:24:06 | 120,636,925 | 0 | 0 | null | null | null | null | UTF-8 | C | false | false | 2,754 | h | /*
* Copyright (c) 2010, Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
*/
/*---------------------------------------------------------------------------*/
#ifndef PROJECT_CONF_H_
#define PROJECT_CONF_H_
/* Comment this out to use Radio Duty Cycle (RDC) and save energy */
#undef NETSTACK_CONF_RDC
#define NETSTACK_CONF_RDC nullrdc_driver
#undef IEEE802154_CONF_PANID
#define IEEE802154_CONF_PANID 0xABCD
#ifndef QUEUEBUF_CONF_NUM
#define QUEUEBUF_CONF_NUM 4
#endif
#undef UIP_CONF_BUFFER_SIZE
#define UIP_CONF_BUFFER_SIZE 256
#ifndef UIP_CONF_RECEIVE_WINDOW
#define UIP_CONF_RECEIVE_WINDOW 60
#endif
#ifndef WEBSERVER_CONF_CFS_CONNS
#define WEBSERVER_CONF_CFS_CONNS 2
#endif
/* The following are Z1 specific */
#undef RF_CHANNEL
#define RF_CHANNEL 26
#undef CC2420_CONF_CHANNEL
#define CC2420_CONF_CHANNEL 26
/* The following are Zoul (RE-Mote, etc) specific */
#undef CC2538_RF_CONF_CHANNEL
#define CC2538_RF_CONF_CHANNEL 26
/* Alternate between ANTENNA_SW_SELECT_SUBGHZ or ANTENNA_SW_SELECT_2_4GHZ */
#define ANTENNA_SW_SELECT_DEF_CONF ANTENNA_SW_SELECT_SUBGHZ
/*---------------------------------------------------------------------------*/
#endif /* PROJECT_CONF_H_ */
| [
"[email protected]"
] | |
ab33aa72c37fd942e9be0ac41d98e227c2abaf25 | d55a83245f0635959694597c65e2391c6f0ce179 | /34.c | db48e41d0380fb2f437e4f7e9d1b7e0af4f55300 | [] | no_license | EmilHernvall/projecteuler | 2cc41492054dba2a88e22cc9b804b6b55c6be54b | e56a4514b8758373c5d83f50cccbc93717cd3f3f | refs/heads/master | 2021-01-21T04:25:00.967621 | 2016-08-10T14:53:47 | 2016-08-10T14:53:47 | 1,697,265 | 1 | 1 | null | null | null | null | UTF-8 | C | false | false | 519 | c | #include <stdio.h>
int factorial(int f)
{
if (f == 0) {
return 1;
}
return (f == 1) ? 1 : (factorial(f-1) * f);
}
int main(void)
{
int factorials[10];
unsigned int i;
for (i = 0; i < 10; i++) {
factorials[i] = factorial(i);
}
unsigned int totalSum = 0, sum, j;
for (i = 10; i < 8*factorials[9]; i++) {
sum = 0;
j = i;
while (j > 0) {
sum += factorials[j%10];
j /= 10;
}
if (sum == i) {
printf("%d\n", i);
totalSum += i;
}
}
printf("total sum: %d\n", totalSum);
return 0;
}
| [
"[email protected]"
] | |
480b59a4b5a324cacd408b0d1c2ba40b4dce38f8 | c0433bd0b21562f781e3c6c50deea45bb8ac892d | /src/atoms/id.h | 07cf043667378850c99dfa93bbfa64dabada90aa | [] | no_license | ahczbhht1989/dragon | 30a30a3bcdc450b9e6793082ce472e331eebf8c2 | 619487398ce8b890b59f8dada6dcc88cb9a4ac91 | refs/heads/master | 2022-11-25T03:58:07.318045 | 2020-07-25T02:43:19 | 2020-07-25T02:43:19 | 282,356,860 | 0 | 0 | null | 2020-07-25T02:42:48 | 2020-07-25T02:42:47 | null | UTF-8 | C | false | false | 340 | h | #ifndef ID_H
#define ID_H
#include "../lib/string.h"
#include "../lib/property-list.h"
#define T Id_t
typedef struct T *T;
T Id_fromString (String_t s);
T Id_bogus ();
T Id_newNoName ();
int Id_hashCode (T x);
void Id_init ();
String_t Id_toString (T x);
int Id_equals (T, T);
Plist_t Id_plist (T);
void Id_print (T);
#undef T
#endif
| [
"[email protected]"
] | |
37485ed4775f2a1fab2db02e6c621a371abbbc6c | fec2a2b11cb000b0345be5bf08a29b46c3465122 | /ChessGUI.h | 30b95a87ad78d0e98a361fffd7e203995cf2b2bb | [] | no_license | jpeezzy/froppy | 86c8f77fb87473490133d350e3055129155bcb8b | a4e593050b23fc8f497167041c8e029f2d387de5 | refs/heads/master | 2021-03-19T16:21:26.106027 | 2018-02-04T08:43:23 | 2018-02-04T08:43:23 | 117,908,152 | 1 | 0 | null | null | null | null | UTF-8 | C | false | false | 1,379 | h | #ifndef CHESSGUI_H
#define CHESSGUI_H
#include "SDL/SDL.h"
/* Global Variables for Screen settings */
#define WIDTH 640 /* width of screen */
#define HEIGHT 640 /* height of screen*/
#define BPP 24 /* bits per pixel */
/* Displays one screen */
void DisplayWindow(char *file, SDL_Surface *screen, int delay);
/* Copies an image to another screen at a certain coordinate */
void Add_Box(SDL_Surface *image, SDL_Surface *screen, int x, int y);
/* Adds to screen directly from a file without using a surface first */
void Add_BoxFile(char *file, SDL_Surface *screen, int x, int y);
/* Updates and keeps window open for while loops */
void UpdateWindow(SDL_Surface *screen, int delay);
/* Creates the tiled board graphic */
void CreateBoard(SDL_Surface *baseBoard, SDL_Surface *tileBoard, SDL_Surface *screen);
/* Copies the tiled board surface to another surface to use as reference */
SDL_Surface *BaseBoardCopy(SDL_Surface *screen, SDL_Rect boardArray[8][8]);
/* Renaming SDL_BlitSurface(), so that it'll be easier for me to re-type it in chunks */
void Move(SDL_Surface *piece, SDL_Rect sprite, SDL_Surface *screen, SDL_Rect rect);
/* Adds the pieces in the intial position onto the board */
//void InitializeBoard(SDL_Surface *pieces, SDL_Surface *screen, SDL_Rect boardArray[8][8]);
/* Exit protocol */
void Exit(SDL_Surface *screen);
#endif
| [
"[email protected]"
] | |
4c65471d054237efadbbc2abcb4b547c6837613e | 546018757d22ae76154b87335db68e1cfabfedcb | /kubernetes/unit-test/test_io_k8s_api_scheduling_v1alpha1_priority_class.c | 91e7bd46df04d2452da329ec0dc748af419ee13d | [
"curl",
"Apache-2.0"
] | permissive | zouxiaoliang/nerv-kubernetes-client-c | 45f1bca75b6265395f144d71bf6866de7b69bc25 | 07528948c643270fd757d38edc68da8c9628ee7a | refs/heads/master | 2023-03-16T09:31:03.072968 | 2021-03-17T07:29:19 | 2021-03-17T07:29:19 | 346,627,883 | 0 | 0 | null | null | null | null | UTF-8 | C | false | false | 2,948 | c | #ifndef io_k8s_api_scheduling_v1alpha1_priority_class_TEST
#define io_k8s_api_scheduling_v1alpha1_priority_class_TEST
// the following is to include only the main from the first c file
#ifndef TEST_MAIN
#define TEST_MAIN
#define io_k8s_api_scheduling_v1alpha1_priority_class_MAIN
#endif // TEST_MAIN
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <stdbool.h>
#include "../external/cJSON.h"
#include "../model/io_k8s_api_scheduling_v1alpha1_priority_class.h"
io_k8s_api_scheduling_v1alpha1_priority_class_t* instantiate_io_k8s_api_scheduling_v1alpha1_priority_class(int include_optional);
#include "test_io_k8s_apimachinery_pkg_apis_meta_v1_object_meta.c"
io_k8s_api_scheduling_v1alpha1_priority_class_t* instantiate_io_k8s_api_scheduling_v1alpha1_priority_class(int include_optional) {
io_k8s_api_scheduling_v1alpha1_priority_class_t* io_k8s_api_scheduling_v1alpha1_priority_class = NULL;
if (include_optional) {
io_k8s_api_scheduling_v1alpha1_priority_class = io_k8s_api_scheduling_v1alpha1_priority_class_create(
"0",
"0",
1,
"0",
// false, not to have infinite recursion
instantiate_io_k8s_apimachinery_pkg_apis_meta_v1_object_meta(0),
"0",
56
);
} else {
io_k8s_api_scheduling_v1alpha1_priority_class = io_k8s_api_scheduling_v1alpha1_priority_class_create(
"0",
"0",
1,
"0",
NULL,
"0",
56
);
}
return io_k8s_api_scheduling_v1alpha1_priority_class;
}
#ifdef io_k8s_api_scheduling_v1alpha1_priority_class_MAIN
void test_io_k8s_api_scheduling_v1alpha1_priority_class(int include_optional) {
io_k8s_api_scheduling_v1alpha1_priority_class_t* io_k8s_api_scheduling_v1alpha1_priority_class_1 = instantiate_io_k8s_api_scheduling_v1alpha1_priority_class(include_optional);
cJSON* jsonio_k8s_api_scheduling_v1alpha1_priority_class_1 = io_k8s_api_scheduling_v1alpha1_priority_class_convertToJSON(io_k8s_api_scheduling_v1alpha1_priority_class_1);
printf("io_k8s_api_scheduling_v1alpha1_priority_class :\n%s\n", cJSON_Print(jsonio_k8s_api_scheduling_v1alpha1_priority_class_1));
io_k8s_api_scheduling_v1alpha1_priority_class_t* io_k8s_api_scheduling_v1alpha1_priority_class_2 = io_k8s_api_scheduling_v1alpha1_priority_class_parseFromJSON(jsonio_k8s_api_scheduling_v1alpha1_priority_class_1);
cJSON* jsonio_k8s_api_scheduling_v1alpha1_priority_class_2 = io_k8s_api_scheduling_v1alpha1_priority_class_convertToJSON(io_k8s_api_scheduling_v1alpha1_priority_class_2);
printf("repeating io_k8s_api_scheduling_v1alpha1_priority_class:\n%s\n", cJSON_Print(jsonio_k8s_api_scheduling_v1alpha1_priority_class_2));
}
int main() {
test_io_k8s_api_scheduling_v1alpha1_priority_class(1);
test_io_k8s_api_scheduling_v1alpha1_priority_class(0);
printf("Hello world \n");
return 0;
}
#endif // io_k8s_api_scheduling_v1alpha1_priority_class_MAIN
#endif // io_k8s_api_scheduling_v1alpha1_priority_class_TEST
| [
"[email protected]"
] | |
f5bcaaad7adc3f955616089c21d523d36a22e098 | a63cb04d1e784d4e9b50284a8a11426abb173887 | /heob.h | 57d1411f4feeaed87f6b6c1601ea980fbd97b6ec | [
"BSL-1.0"
] | permissive | ssbssa/heob | 94be93931a30866de071e2823c0452c6369e9f4f | e86be917b60a9c4cb0e516c4b5cf942cbb0beefe | refs/heads/master | 2023-08-16T22:36:53.620635 | 2023-08-06T11:39:02 | 2023-08-06T12:47:38 | 42,008,939 | 135 | 31 | BSL-1.0 | 2021-06-29T15:13:39 | 2015-09-06T16:10:38 | C | UTF-8 | C | false | false | 1,483 | h |
// Copyright Hannes Domani 2018-2023.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef __HEOB_H__
#define __HEOB_H__
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
// input commands for heob_control()
enum
{
// stop leak recording
HEOB_LEAK_RECORDING_STOP,
// start leak recording
HEOB_LEAK_RECORDING_START,
// clear all recorded leaks
HEOB_LEAK_RECORDING_CLEAR,
// show all recorded leaks
HEOB_LEAK_RECORDING_SHOW,
// return if leak recording is enabled
HEOB_LEAK_RECORDING_STATE,
// return number of recorded leaks
HEOB_LEAK_COUNT,
};
// error return values of heob_control()
enum
{
// heob was configured to handle exceptions only
HEOB_HANDLE_EXCEPTIONS_ONLY = -1,
// target process doesn't use a CRT
HEOB_NO_CRT_FOUND = -2,
// invalid command
HEOB_INVALID_CMD = -3,
// process was not started with heob
HEOB_NOT_FOUND = -1024,
};
#ifndef HEOB_INTERNAL
#ifndef _WIN64
#define HEOB_BITS "32"
#else
#define HEOB_BITS "64"
#endif
typedef int func_heob_control( int );
static inline int heob_control( int cmd )
{
HMODULE heob = GetModuleHandleA( "heob" HEOB_BITS ".exe" );
func_heob_control *fheob_control = heob ?
(func_heob_control*)GetProcAddress( heob,"heob_control" ) : NULL;
if( !fheob_control )
return( HEOB_NOT_FOUND );
return( fheob_control(cmd) );
}
#endif
#endif
| [
"[email protected]"
] | |
52f8c8ad5fdcdb0b3c3aaff68e66ae5c86d7dd35 | 35d43f7ffbf6087edcdf131fdef10dbc04a53905 | /app/include/fanet/pollmng.h | e5cca42220cce3d11e563b1acf36affa29c1cdc8 | [] | no_license | kimhyunki/sw | b62dac528c914e80ba396fccc81717d95d98da72 | a63c90a920260bd202ff2740958ebc9c4ecbfba9 | refs/heads/master | 2022-02-17T07:30:57.485558 | 2020-10-27T02:12:56 | 2020-10-27T02:12:56 | 93,709,423 | 0 | 0 | null | 2022-01-15T06:04:16 | 2017-06-08T05:07:05 | Batchfile | UTF-8 | C | false | false | 607 | h | /*
* file pollmng.h
* date 2019-09-30
* auther 김현기 [email protected]
* brief poll manager
*/
#ifndef _POLL_MNG_H_
#define _POLL_MNG_H_
#define STYP_FILE 5
void poll_init (void);
typedef struct poll_obj poll_obj_t;
struct poll_obj{
int fd;
int type;
int tag;
void *socket;
void *user;
int (*on_poll_in) (poll_obj_t *obj);
int (*on_poll_out) (poll_obj_t *obj);
int (*on_poll_err( (poll_obj_t *obj);
int (*on_poll_hup) (poll_obj_t *obj);
int (*on_timeout) (poll_obj_t *obj);
};
typedef struct poll_obj poll_obj_t;
#endif // _POLL_MNG_H_
| [
"[email protected]"
] | |
cb5655b7377c6acaf979b5a15114b8150270bacd | 370a7847ee047dfe5c11a8dfa8272d9fd333b911 | /LinuxDriver/JZ2440/norflash设备驱动/s3c_nor.c | a14828fe6831c17d79e9f0701816279a4dcdec6e | [] | no_license | TimChanCHN/LinuxProgram | d2e3e8b70d90d1a9956628086419949c2570af82 | 67082ba23a21033d903c94a642673d64115ed756 | refs/heads/master | 2020-07-28T19:05:15.158684 | 2020-04-24T10:51:23 | 2020-04-24T10:51:23 | 209,504,126 | 0 | 0 | null | null | null | null | UTF-8 | C | false | false | 2,000 | c | #include <linux/module.h>
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/device.h>
#include <linux/platform_device.h>
#include <linux/mtd/mtd.h>
#include <linux/mtd/map.h>
#include <linux/mtd/partitions.h>
#include <linux/mtd/physmap.h>
#include <linux/mtd/concat.h>
#include <linux/io.h>
#define NOR_BASE_ADDRESS 0
static struct map_info* s3c_nor_map;
static struct mtd_info* s3c_nor_mtd;
static struct mtd_partition s3c_nor_part[] = {
[0] = {
.name = "bootloader_nor",
.size = 0x00040000,
.offset = 0,
},
[1] = {
.name = "rootfs_nor",
.offset = MTDPART_OFS_APPEND,
.size = MTDPART_SIZ_FULL,
}
};
static int __init s3c_nor_init(void)
{
/* 1. 分配map_info结构体 */
s3c_nor_map = kzalloc(sizeof(struct map_info), GFP_KERNEL);
/* 2. 设置:物理基地址,大小,位宽,虚拟基地址 */
s3c_nor_map->name = "s3c_nor";
s3c_nor_map->phys = 0;
s3c_nor_map->size = 0x1000000; /* 16M,要大于nor flash 的实际大小 */
s3c_nor_map->bankwidth = 2; /* 最小位宽是8,此处填8的倍数 */
s3c_nor_map->virt = ioremap(s3c_nor_map->phys, s3c_nor_map->size);
simple_map_init(s3c_nor_map);
/* 3. 使用NOR FLASH协议层提供的函数来识别nor flash */
printk("using cfi \n");
s3c_nor_mtd = do_map_probe("cfi_probe", s3c_nor_map);
if( !s3c_nor_mtd )
{
printk("turn to using jedec \n");
s3c_nor_mtd = do_map_probe("jedec_probe", s3c_nor_map);
}
if( !s3c_nor_mtd )
{
printk("do map probe fail\n");
iounmap(s3c_nor_map->virt);
kfree(s3c_nor_map);
return -EIO;
}
/* 4. add_mtdpartition */
mtd_device_parse_register(s3c_nor_mtd, NULL, NULL, s3c_nor_part, 2);
return 0;
}
static void __exit s3c_nor_exit(void)
{
mtd_device_unregister(s3c_nor_mtd);
iounmap(s3c_nor_map->virt);
kfree(s3c_nor_map);
}
module_init(s3c_nor_init);
module_exit(s3c_nor_exit);
MODULE_LICENSE("GPL");
| [
"[email protected]"
] | |
8355b0010ae70b019f2b34b18cdfe44801452f21 | e0dce78337ac29a83d9fdb675421917d6b19ed74 | /HW3/echoserver_select.c | b8c80b87315e6312fa028b68bc05eacfa2d7e464 | [] | no_license | aynoor25/CSE508_HWs | 26735d3130df8882122fd78307fb0a42b850520b | 6a184c9fd1278d08acdce81a58fd7118979d67aa | refs/heads/master | 2021-05-12T12:21:38.044645 | 2018-01-14T06:51:14 | 2018-01-14T06:51:14 | 117,408,574 | 0 | 0 | null | null | null | null | UTF-8 | C | false | false | 4,662 | c | /* multi-client-echo-server.c - a multi-client echo server */
#include <stdio.h> /* Basic I/O routines */
#include <sys/types.h> /* standard system types */
#include <netinet/in.h> /* Internet address structures */
#include <sys/socket.h> /* socket interface functions */
#include <netdb.h> /* host to IP resolution */
#include <sys/time.h> /* for timeout values */
#include <unistd.h> /* for table size calculations */
#include <string.h>
#define PORT 3232 /* port of our echo server */
#define BUFLEN 1024 /* buffer length */
int strupp(char *s) {
int i;
for (i = 0; i < strlen(s); i++)
s[i] = toupper(s[i]);
return i;
}
void main()
{
int i; /* index counter for loop operations */
int rc; /* system calls return value storage */
int s; /* socket descriptor */
int cs; /* new connection's socket descriptor */
char buf[BUFLEN+1]; /* buffer for incoming data */
struct sockaddr_in sa; /* Internet address struct */
struct sockaddr_in csa; /* client's address struct */
int size_csa; /* size of client's address struct */
fd_set rfd; /* set of open sockets */
fd_set c_rfd; /* set of sockets waiting to be read */
int dsize; /* size of file descriptors table */
/* initiate machine's Internet address structure */
/* first clear out the struct, to avoid garbage */
memset(&sa, 0, sizeof(sa));
/* Using Internet address family */
sa.sin_family = AF_INET;
/* copy port number in network byte order */
sa.sin_port = htons(PORT);
/* we will accept cnnections coming through any IP */
/* address that belongs to our host, using the */
/* INADDR_ANY wild-card. */
sa.sin_addr.s_addr = INADDR_ANY;
/* allocate a free socket */
/* Internet address family, Stream socket */
s = socket(AF_INET, SOCK_STREAM, 0);
if (s < 0) {
perror("socket: allocation failed");
}
/* bind the socket to the newly formed address */
rc = bind(s, (struct sockaddr *)&sa, sizeof(sa));
/* check there was no error */
if (rc) {
perror("bind");
}
/* ask the system to listen for incoming connections */
/* to the address we just bound. specify that up to */
/* 5 pending connection requests will be queued by the */
/* system, if we are not directly awaiting them using */
/* the accept() system call, when they arrive. */
rc = listen(s, 5);
/* check there was no error */
if (rc) {
perror("listen");
}
/* remember size for later usage */
size_csa = sizeof(csa);
/* calculate size of file descriptors table */
dsize = getdtablesize();
/* close all file descriptors, except our communication socket */
/* this is done to avoid blocking on tty operations and such. */
for (i=0; i<dsize; i++)
if (i != s)
close(i);
/* we innitialy have only one socket open, */
/* to receive new incoming connections. */
FD_ZERO(&rfd);
FD_SET(s, &rfd);
/* enter an accept-write-close infinite loop */
while (1) {
/* the select() system call waits until any of */
/* the file descriptors specified in the read, */
/* write and exception sets given to it, is */
/* ready to give data, send data, or is in an */
/* exceptional state, in respect. the call will */
/* wait for a given time before returning. in */
/* this case, the value is NULL, so it will */
/* not timeout. dsize specifies the size of the */
/* file descriptor table. */
c_rfd = rfd;
printf("Wating for new connnections");
rc = select(dsize, &c_rfd, NULL, NULL, (struct timeval *)NULL);
/* if the 's' socket is ready for reading, it */
/* means that a new connection request arrived. */
if (FD_ISSET(s, &c_rfd)) {
/* accept the incoming connection */
cs = accept(s, (struct sockaddr *)&csa, &size_csa);
/* check for errors. if any, ignore new connection */
if (cs < 0)
continue;
/* add the new socket to the set of open sockets */
FD_SET(cs, &rfd);
/* and loop again */
continue;
}
/* check which sockets are ready for reading, */
/* and handle them with care. */
for (i=0; i<dsize; i++)
if (i != s && FD_ISSET(i, &c_rfd)) {
/* read from the socket */
rc = read(i, buf, BUFLEN);
printf("%s\n", buf);
/* if client closed the connection... */
if (rc == 0) {
/* close the socket */
close(i);
FD_CLR(i, &rfd);
}
/* if there was data to read */
else {
/* echo it back to the client */
strupp(buf);
write(i, buf, rc);
}
}
}
}
| [
"[email protected]"
] | |
264a883eb9754c7eb73d21d289d95a05ccaa1df9 | 3b07cb35e420f3c197a0408ff81a29390d322f38 | /6502/handout/instruction.h | 79e7d626ed56a98bbdf6cc749fb416a1b6c7cd9d | [] | no_license | bjcworth/6502-Emulator | af6737ad8a03935aaecf18cb1d226d14f077a3f0 | 8d3e51d1e8284160dcf5c053693f4fa2660a196a | refs/heads/master | 2021-01-10T21:23:10.154806 | 2014-03-27T19:31:11 | 2014-03-27T19:31:11 | 18,188,486 | 1 | 0 | null | null | null | null | UTF-8 | C | false | false | 6,431 | h | #ifndef __INSTRUCTION_H__
#define __INSTRUCTION_H__
/******************************************************************************
* Copyright (C) 2011 by Jonathan Appavoo, Boston University
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*****************************************************************************/
// Following info from http://www.masswerk.at/6502/6502_instruction_set.html
/* Address Modes: */
/* A Accumulator OPC A operand is AC */
/* abs absolute OPC $HHLL operand is address $HHLL */
/* abs,X absolute, X-indexed OPC $HHLL,X operand is address incremented
by X with carry */
/* abs,Y absolute, Y-indexed OPC $HHLL,Y operand is address incremented
by Y with carry */
/* # immediate OPC #$BB operand is byte (BB) */
/* impl implied OPC operand implied */
/* ind indirect OPC ($HHLL) operand is effective address;
effective address is value of address */
/* X,ind X-indexed, indirect OPC ($BB,X) operand is effective zeropage address;
effective address is byte (BB)
incremented by X without carry */
/* ind,Y indirect, Y-indexed OPC ($LL),Y operand is effective address incremented
by Y with carry;
effective address is word at zeropage
address */
/* rel relative OPC $BB branch target is PC + offset (BB),
bit 7 signifies negative offset */
/* zpg zeropage OPC $LL operand is of address;
address hibyte = zero ($00xx) */
/* zpg,X zeropage, X-indexed OPC $LL,X operand is address incremented by X;
address hibyte = zero ($00xx);
no page transition */
/* zpg,Y zeropage, Y-indexed OPC $LL,Y operand is address incremented by Y;
address hibyte = zero ($00xx);
no page transition */
enum AddressingMode {
INVALIDAM=0, // SYNTHETIC INVALID ADDRESSING MODE
ACC, // A: Accumulator A
ABS, // abs: Absolute a
ABSX, // abs,X: Absolute Indexed with X a,x
ABSY, // abs,Y: Absolute Indexed with Y a,y
IMM, // #: Immediate #
IMPL, // impl: Implied i
IND, // ind: Absolute Indirect (a)
XIND, // X,ind: Zero Page Index Indirect (zp,x)
INDY, // ind,Y: Zero Page Indirect Indexed with Y (zp),y
REL, // rel: Program Counter Relative r
ZP, // zpg: Zero Page zp
ZPX, // zpg,X: Zero Page Index with X
ZPY, // zpg,Y: Zero Page Index with Y
};
struct AddressingModeDesc;
typedef int (*amfunc)(struct AddressingModeDesc *mode, struct machine *m);
struct AddressingModeDesc {
enum AddressingMode mode;
amfunc func;
char bytes; // number of bytes this address mode format
// ocupies, including the opcode itself.
// pc plus this number of bytes get you to the
// next opcode
char desc[80];
char prfmt[20];
};
extern struct AddressingModeDesc AMTable[];
enum Instruction {
INV,
ADC, AND, ASL,
BCC, BCS, BEQ, BIT, BMI, BNE, BPL, BRK, BVC, BVS,
CLC, CLD, CLI, CLV, CMP, CPX, CPY,
DEC, DEX, DEY,
EOR,
INC, INX, INY,
JMP, JSR,
LDA, LDX, LDY, LSR,
NOP,
ORA,
PHA, PHP, PLA, PLP,
ROL, ROR, RTI, RTS,
SBC, SEC, SED, SEI, STA, STX, STY,
TAX, TAY, TSX, TXA, TXS, TYA
};
struct InstructionDesc {
enum Instruction inst;
char memonic[4];
char description[80];
};
extern struct InstructionDesc InstTable[];
#define NUMOPCODES 256
typedef byte opcode;
struct OPCodeDesc;
typedef int (*instfunc)(struct OPCodeDesc *op, struct machine *m);
// I HAVE CHOOSEN TO USE 0x02 AS THE INVALID OPCODE SIGNATURE
// WHICH IS THE FIRST UNUSED OPCODE THAT I COULD FIND THAT SHOULD
// BE TREATED AS KIL OPCODE (see http://www.pagetable.com/?p=39)
// REQUIRING A PROCESSOR RESET
#define INVALIDOPCODE 0x02
struct OPCodeDesc {
opcode op;
struct AddressingModeDesc *am;
byte SRBits;
instfunc func;
struct InstructionDesc *ins;
};
extern struct OPCodeDesc OPCodeTable[NUMOPCODES];
static inline char * inst_memonic(byte opcode) { return OPCodeTable[opcode].ins->memonic; }
static inline struct AddressingModeDesc * inst_addressingmode(byte opcode) {
return OPCodeTable[opcode].am;
}
static inline byte inst_srbits(byte opcode) { return OPCodeTable[opcode].SRBits; }
static inline int inst_isvalid(byte opcode) { return OPCodeTable[opcode].op != INV; }
static inline void inst_push(struct machine *m, byte v) {
address addr=0;
ADDR_SET_HIGH(addr, STACK_PAGE);
ADDR_SET_LOW(addr, m->cpu.reg.sp);
mem_put(m, addr, v);
m->cpu.reg.sp--;
}
static inline byte inst_pop(struct machine *m){
address addr=0;
m->cpu.reg.sp++;
ADDR_SET_HIGH(addr, STACK_PAGE);
ADDR_SET_LOW(addr, m->cpu.reg.sp);
return mem_get(m, addr);
}
#endif
| [
"[email protected]"
] | |
da9ce62c4cb3a15f08fde9092df0905ffe64882c | 26bc74369bf684c4d46a39773b3e74bd005bff19 | /Armlet_fw/os/hal/hal.h | c0d02a964103907480226de58232fe3477768a5b | [] | no_license | Kreyl/Generation | 4c57c8cfb437b4ec7569ba392239ad6052131509 | 2fb4d2e27c199847a0018561f61028efc35fa8db | refs/heads/master | 2021-01-20T22:45:36.168554 | 2019-02-24T14:09:30 | 2019-02-24T14:09:30 | 54,397,215 | 0 | 0 | null | null | null | null | UTF-8 | C | false | false | 4,027 | h | /*
ChibiOS - Copyright (C) 2006..2015 Giovanni Di Sirio
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/**
* @file hal.h
* @brief HAL subsystem header.
*
* @addtogroup HAL
* @{
*/
#ifndef _HAL_H_
#define _HAL_H_
#include "osal.h"
#include "board.h"
#include "halconf.h"
#include "hal_lld.h"
/* Abstract interfaces.*/
#include "hal_streams.h"
#include "hal_channels.h"
#include "hal_files.h"
#include "hal_ioblock.h"
//#include "hal_mmcsd.h" // @KL
/* Shared headers.*/
#include "hal_buffers.h"
#include "hal_queues.h"
/* Normal drivers.*/
//#include "ext.h"
//#include "gpt.h"
//#include "i2c.h"
//#include "i2s.h"
//#include "icu.h"
//#include "mac.h"
//#include "mii.h"
//#include "pwm.h"
//#include "rtc.h"
//#include "serial.h"
//#include "sdc.h"
//#include "spi.h"
//#include "uart.h"
#include "usb.h"
//#include "wdg.h"
/*
* The ST driver is a special case, it is only included if the OSAL is
* configured to require it.
*/
#if OSAL_ST_MODE != OSAL_ST_MODE_NONE
#include "st.h"
#endif
/* Complex drivers.*/
//#include "mmc_spi.h"
//#include "serial_usb.h"
/* Community drivers.*/
#if defined(HAL_USE_COMMUNITY) || defined(__DOXYGEN__)
#if (HAL_USE_COMMUNITY == TRUE) || defined(__DOXYGEN__)
#include "hal_community.h"
#endif
#endif
/*===========================================================================*/
/* Driver constants. */
/*===========================================================================*/
/**
* @brief ChibiOS/HAL identification macro.
*/
#define _CHIBIOS_HAL_
/**
* @brief Stable release flag.
*/
#define CH_HAL_STABLE 1
/**
* @name ChibiOS/HAL version identification
* @{
*/
/**
* @brief HAL version string.
*/
#define HAL_VERSION "4.0.4"
/**
* @brief HAL version major number.
*/
#define CH_HAL_MAJOR 4
/**
* @brief HAL version minor number.
*/
#define CH_HAL_MINOR 0
/**
* @brief HAL version patch number.
*/
#define CH_HAL_PATCH 4
/** @} */
/**
* @name Return codes
* @{
*/
#define HAL_SUCCESS false
#define HAL_FAILED true
/** @} */
/*===========================================================================*/
/* Driver pre-compile time settings. */
/*===========================================================================*/
/*===========================================================================*/
/* Derived constants and error checks. */
/*===========================================================================*/
/*===========================================================================*/
/* Driver data structures and types. */
/*===========================================================================*/
/*===========================================================================*/
/* Driver macros. */
/*===========================================================================*/
/*===========================================================================*/
/* External declarations. */
/*===========================================================================*/
#ifdef __cplusplus
extern "C" {
#endif
void halInit(void);
#ifdef __cplusplus
}
#endif
#endif /* _HAL_H_ */
/** @} */
| [
"[email protected]"
] | |
c2e3ca62aaa790f3169c90fcfef607f4980fea05 | 2e7bfbe9a604ec92e0023a7ad6785b382270e6c3 | /SiCMiC/Test/mainx.c | c7e53b39fae503d7638cfc48e7ed34ef44ec63b5 | [] | no_license | darag90/SiCProject | b5f460d065e36dc0ea19f2e30be0c7ed22404e53 | 4559a0b3cf4d53d3f07f318da8d0f72bab7be232 | refs/heads/master | 2020-05-07T13:02:02.140924 | 2018-11-07T16:08:00 | 2018-11-07T16:08:00 | null | 0 | 0 | null | null | null | null | UTF-8 | C | false | false | 7,163 | c |
/**
******************************************************************************
* @file : main.c
* @brief : Main program body
******************************************************************************
** This notice applies to any and all portions of this file
* that are not between comment pairs USER CODE BEGIN and
* USER CODE END. Other portions of this file, whether
* inserted by the user or by software development tools
* are owned by their respective copyright owners.
*
* COPYRIGHT(c) 2018 STMicroelectronics
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of STMicroelectronics nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "stm32l0xx_hal.h"
#include "adc.h"
#include "dac.h"
#include "i2c.h"
#include "iwdg.h"
#include "usart.h"
#include "gpio.h"
/* USER CODE BEGIN Includes */
/* USER CODE END Includes */
/* Private variables ---------------------------------------------------------*/
/* USER CODE BEGIN PV */
/* Private variables ---------------------------------------------------------*/
/* USER CODE END PV */
/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
/* USER CODE BEGIN PFP */
/* Private function prototypes -----------------------------------------------*/
/* USER CODE END PFP */
/* USER CODE BEGIN 0 */
/* USER CODE END 0 */
/**
* @brief The application entry point.
*
* @retval None
*/
int main(void)
{
/* USER CODE BEGIN 1 */
/* USER CODE END 1 */
/* MCU Configuration----------------------------------------------------------*/
/* Reset of all peripherals, Initializes the Flash interface and the Systick. */
HAL_Init();
/* USER CODE BEGIN Init */
/* USER CODE END Init */
/* Configure the system clock */
SystemClock_Config();
/* USER CODE BEGIN SysInit */
/* USER CODE END SysInit */
/* Initialize all configured peripherals */
MX_GPIO_Init();
MX_ADC_Init();
MX_DAC_Init();
MX_I2C1_Init();
MX_USART1_UART_Init();
MX_IWDG_Init();
/* USER CODE BEGIN 2 */
/* USER CODE END 2 */
/* Infinite loop */
/* USER CODE BEGIN WHILE */
while (1)
{
/* USER CODE END WHILE */
/* USER CODE BEGIN 3 */
}
/* USER CODE END 3 */
}
/**
* @brief System Clock Configuration
* @retval None
*/
void SystemClock_Config(void)
{
RCC_OscInitTypeDef RCC_OscInitStruct;
RCC_ClkInitTypeDef RCC_ClkInitStruct;
RCC_PeriphCLKInitTypeDef PeriphClkInit;
/**Configure the main internal regulator output voltage
*/
__HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE1);
/**Initializes the CPU, AHB and APB busses clocks
*/
RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI|RCC_OSCILLATORTYPE_LSI
|RCC_OSCILLATORTYPE_MSI;
RCC_OscInitStruct.HSIState = RCC_HSI_DIV4;
RCC_OscInitStruct.HSICalibrationValue = 16;
RCC_OscInitStruct.LSIState = RCC_LSI_ON;
RCC_OscInitStruct.MSIState = RCC_MSI_ON;
RCC_OscInitStruct.MSICalibrationValue = 0;
RCC_OscInitStruct.MSIClockRange = RCC_MSIRANGE_5;
RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE;
if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
{
_Error_Handler(__FILE__, __LINE__);
}
/**Initializes the CPU, AHB and APB busses clocks
*/
RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
|RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_MSI;
RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1;
RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;
if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_0) != HAL_OK)
{
_Error_Handler(__FILE__, __LINE__);
}
PeriphClkInit.PeriphClockSelection = RCC_PERIPHCLK_USART1|RCC_PERIPHCLK_I2C1;
PeriphClkInit.Usart1ClockSelection = RCC_USART1CLKSOURCE_PCLK2;
PeriphClkInit.I2c1ClockSelection = RCC_I2C1CLKSOURCE_HSI;
if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInit) != HAL_OK)
{
_Error_Handler(__FILE__, __LINE__);
}
/**Configure the Systick interrupt time
*/
HAL_SYSTICK_Config(HAL_RCC_GetHCLKFreq()/1000);
/**Configure the Systick
*/
HAL_SYSTICK_CLKSourceConfig(SYSTICK_CLKSOURCE_HCLK);
/* SysTick_IRQn interrupt configuration */
HAL_NVIC_SetPriority(SysTick_IRQn, 0, 0);
}
/* USER CODE BEGIN 4 */
/* USER CODE END 4 */
/**
* @brief This function is executed in case of error occurrence.
* @param file: The file name as string.
* @param line: The line in file as a number.
* @retval None
*/
void _Error_Handler(char *file, int line)
{
/* USER CODE BEGIN Error_Handler_Debug */
/* User can add his own implementation to report the HAL error return state */
while(1)
{
}
/* USER CODE END Error_Handler_Debug */
}
#ifdef USE_FULL_ASSERT
/**
* @brief Reports the name of the source file and the source line number
* where the assert_param error has occurred.
* @param file: pointer to the source file name
* @param line: assert_param error line source number
* @retval None
*/
void assert_failed(uint8_t* file, uint32_t line)
{
/* USER CODE BEGIN 6 */
/* User can add his own implementation to report the file name and line number,
ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
/* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */
/**
* @}
*/
/**
* @}
*/
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
| [
"[email protected]"
] | |
c5627b54202bd497d746e9c3b12ee515b6b3d6d4 | 263442715136106570ac9953245a1ec9e8fe4325 | /gsh.c | bf02cc4f40c917278039a3d596a36631a7dd287a | [] | no_license | core-dumper/gsh | 779f6cf92cb7e0445fe63f0b3036bc78a60d101c | b5fd500d08ade2dcfe4a873a2acce08b32ad1c7f | refs/heads/master | 2022-06-01T21:16:16.621499 | 2020-04-20T00:34:49 | 2020-04-20T00:34:49 | 260,849,356 | 0 | 0 | null | 2020-05-03T07:21:04 | 2020-05-03T07:21:04 | null | UTF-8 | C | false | false | 1,456 | c | #include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <unistd.h>
#include <readline/readline.h>
#include <readline/history.h>
#include <errno.h>
#define BUFF_S 1024
#define DELIM " \t\n\r"
char **split_line(char *line){
int buffsize = BUFF_S , position = 0;
char **args = malloc(sizeof(buffsize) * sizeof(char *));
char *arg;
if(!args){
perror("args");
exit(EXIT_FAILURE);}
arg = strtok(line,DELIM);
while(arg != NULL){
args[position] = arg;
position++;
if(position >= buffsize){
buffsize += BUFF_S;
args = realloc(args,buffsize*sizeof(char*));
if(!args){
perror("args");
exit(EXIT_FAILURE);}}
arg = strtok(NULL,DELIM);
}
args[position] = NULL;
return args;
}
void cd(char *path){
int stat;
if(path == NULL){
stat = chdir(getenv("HOME"));}
else{ stat = chdir(path);}
if(stat == -1){
perror("cd");
}
}
void gexit(){
exit(EXIT_SUCCESS);
}
int main(){
char *line,*prompt=" => ";
while(1){
char * pwd = getcwd(0,0);
strcat(pwd,prompt);
line = readline(pwd);
if(strcmp(line,"")==0){free(line) ; continue;}
if(strcmp(line,"exit")==0){free(line); gexit();}
add_history(line);
char **args=split_line(line);
if(strcmp(args[0],"cd")==0){
cd(args[1]);
free(line);
continue;}
pid_t cpid = fork();
if(cpid == 0){
if((execvp(args[0],args)) < 0){
perror("gsh");}
}if(cpid > 0){wait(NULL);}
free(line);
free(args);
}
}
| [
"[email protected]"
] | |
6c32e5ed54ca22436d6cfa5fa79ee004594c5737 | 5b7d43971eae9f06b81d4c2ae37a12d667b696b3 | /mudlib/d/taiping/house2.c | 16cc10d0033ff2c1ea6e0f1c011dd269360d4d8a | [] | no_license | lostsailboard/fy4 | cb6ad743fa0e6dec045e4d5c419b358888fc6a36 | b79d809c6e13d49e8bc878302512ad0d18a3e151 | refs/heads/master | 2021-12-08T06:03:29.100438 | 2016-02-21T09:03:58 | 2016-02-21T09:03:58 | null | 0 | 0 | null | null | null | null | GB18030 | C | false | false | 1,084 | c | #include <ansi.h>
inherit ROOM;
void create()
{
set("short", "商人居");
set("long", @LONG
小街两侧是一排平房,西北最普通,最常见的砖土四合院,住在这里的大多数
是靠手艺吃饭的,有开小杂货铺的,理发的,打铁的,伐木的。或者就像这间的主
人,常年奔波于塞外和中原做生意,最终女人耐不住寂寞改嫁了,除了逢年过节探
亲的时候,屋子就一直空关着,墙上用炭粉歪歪扭扭写了几行字。
LONG
);
set("exits", ([
"east" : __DIR__"mroad45",
]));
set("item_desc", ([
"墙": "墙上用炭粉歪歪扭扭写了几行字“重利轻离别,我好悔也!”\n",
"wall": "墙上用炭粉歪歪扭扭写了几行字“重利轻离别,我好悔也!”\n",
]));
set("objects", ([
]));
set("coor/x",0);
set("coor/y",0);
set("coor/z",0);
setup();
}
| [
"[email protected]"
] | |
de849e3393adb2ae9be5d0271aeae3bd45e2c1e4 | 001a11ca541e6b3fb17373420a1647ad0d673abf | /Input & Output 2.c | 094ec57905bec1e18d49f87a0c159e749b42699e | [] | no_license | vardhanrajya08/ELAB_C_LVL_1 | 3fd1acec62f15853d51825896bb9b2d39c74db28 | 43acf83dcc78338c99d46980f06d0673794649fe | refs/heads/main | 2023-07-13T06:04:05.270625 | 2021-08-06T04:34:49 | 2021-08-06T04:34:49 | 386,349,423 | 0 | 0 | null | null | null | null | UTF-8 | C | false | false | 3,182 | c | // Ratik a young millionaire deposits $10000 into a bank account paying 7% simple interest per year.
#include <stdio.h>
int main()
{
float p,i,interest,amount;
int t;
scanf("%f %f %d",&p,&i,&t);
interest=(p*i*t)/100;
amount=p+interest;
printf("Interest after %d Years = $%0.2f\n",t,interest);
printf("Total Amount after %d Years = $%0.2f",t,amount);
return 0;
}
// Flipkart announced the year end stock clearance sale and as apart of they have also conducting the contest and the users answering the questions asked in the contest can win Moto One Power free of cost.
#include <stdio.h>
#include <math.h>
int main()
{
int N,fp,sp,tp;
scanf("%d",&N);
fp=pow(N,1);
sp=pow(N,2);
tp=pow(N,3);
printf("%d %d %d",fp,sp,tp);
return 0;
}
// Roopa and Atifa are sisters they love to compete by playing math games which gradually helped them in their academics one day.
#include <stdio.h>
int main()
{
float num1,num2;
int sum;
scanf("%f\n %f",&num1,&num2);
sum=(int)num1+num2;
printf("%d",sum);
return 0;
}
// Salima saw a pair of beautiful dress online but she was confused about the metric system used for the size of the dress.
#include <stdio.h>
int main()
{
int feet,inches;
float cms;
scanf("%d %d",&feet,&inches);
cms=feet*12*2.54+inches*2.54;
printf("Your height in centimeters is : %0.2f",cms);
return 0;
}
// Karthik was working in the HR division of Audi.#include <stdio.h>
int main()
{
double salaryperday,totsalary;
int hour;
scanf("%d\n %lf",&hour,&salaryperday);
totsalary=hour*salaryperday;
printf("%.2lf",totsalary);
return 0;
}
// Nathan was a student by morning and a computer nerd by night .
#include <stdio.h>
int main()
{
int prodid,billid,quantity;
float price,totprice;
scanf("%d\n %d\n %f\n %d",&billid,&prodid,&price,&quantity);
totprice=quantity*price;
printf("%0.2f",totprice);
return 0;
}
// Ram was working as a Marketing Executive in Pepsi.
#include <stdio.h>
int main()
{
int km;
float lpd;
float result;
scanf("%d\n %f",&km,&lpd);
result=km/lpd;
printf("%.3f",result);
return 0;
}
// Arulmozhivarman's Dream came true after he got an Appointment order from Google.Simon's family was very happy of his achievement.
#include <stdio.h>
int main()
{
int GrossPayment,basic,da,hra;
scanf("%d %d %d",&basic,&da,&hra);
GrossPayment=(basic*(da+hra)/100)+basic;
double s=GrossPayment-0.5;
printf("%.lf",s);
return 0;
}
// Arul and Kani own the farm in the beautiful location of the city were lot of cows was roaming around. One day Arul and Kani was out of the city. On that day cows have eaten the grasses in the farm which is circular in structure.
#include <stdio.h>
int main()
{
float rad;
float PI=3.14,area,ci;
scanf("%f",&rad);
area=PI*rad*rad;
ci=2*PI*rad;
printf("%.2f\n%.2f",area,ci);
return 0;
}
// Jannu and Preethi both went to Egypt for visiting Pyramids.
#include <stdio.h>
int main()
{
float base,height,area;
scanf("%f %f",&height,&base);
area=(base*height)/2;
printf("%0.3f",area);
return 0;
}
| [
"[email protected]"
] | |
6dac355a7e16f424fd2e0222864b0c1caae78c85 | 5c255f911786e984286b1f7a4e6091a68419d049 | /code/40682cc2-53c4-41d5-a0b3-e294283aa5e6.c | 49ac8c01898ff1ba387131888ad29c39da45d258 | [] | no_license | nmharmon8/Deep-Buffer-Overflow-Detection | 70fe02c8dc75d12e91f5bc4468cf260e490af1a4 | e0c86210c86afb07c8d4abcc957c7f1b252b4eb2 | refs/heads/master | 2021-09-11T19:09:59.944740 | 2018-04-06T16:26:34 | 2018-04-06T16:26:34 | 125,521,331 | 0 | 0 | null | null | null | null | UTF-8 | C | false | false | 242 | c | #include <stdio.h>
int main() {
int i=44;
int j=12;
int k;
int l;
k = 53;
l = 64;
k = i/j;
l = i/j;
l = l/j;
l = l%j;
l = l-j;
k = k-j*i;
printf("vulnerability");
printf("%d%d\n",k,l);
return 0;
}
| [
"[email protected]"
] | |
5bc1e59c62c6874b67f88032c076067fcd6f0f92 | 22da74b973ca31f4c44b8146b029749181d5d946 | /Tabboz Simulator/C/net.c | 77bf805ef2726f23734871152e16a2235ad6c7d2 | [] | no_license | biappi/Tabboz-Simulator | fd0ac386052a8b1c6291867756c28ae27c4a7bf2 | ba701d93d5169db5289113964c06545264dc32dd | refs/heads/master | 2021-07-06T22:24:29.405899 | 2019-02-22T13:05:28 | 2019-02-22T13:05:28 | 169,935,804 | 3 | 0 | null | null | null | null | UTF-8 | C | false | false | 11,210 | c | // Tabboz Simulator
// (C) Copyright 1998 by Andrea Bonomi
// Iniziato il 24 Giugno 1998
// 5 Gigno 1999 - Conversione Tabbozzo -> Tabbozza
/*
This file is part of Tabboz Simulator.
Tabboz Simulator is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Nome-Programma is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Nome-Programma. If not, see <http://www.gnu.org/licenses/>.
*/
#include "os.h"
#ifdef TABBOZ_WIN
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <conio.h>
#include <process.h>
#include <time.h>
#include "zarrosim.h"
#include "net.h"
static char sccsid[] = "@(#)" __FILE__ " " VERSION " (Andrea Bonomi) " __DATE__;
#ifndef NONETWORK /* ---------------------------------------------------------------------------*/
/* global variable */
int swivel_angle,pitch_angle,yaw_angle;
/* function prototype */
void SendReceiveToClient(void *cs);
void transferData(char []);
WSADATA Data;
SOCKADDR_IN serverSockAddr;
SOCKADDR_IN clientSockAddr;
SOCKET serverSocket;
SOCKET clientSocket;
int addrLen = sizeof(SOCKADDR_IN);
int status;
int net_enable;
char lastconnect[255];
char lastneterror[255];
HWND NEThDlg;
int PortNumber;
/**************************************************************/
void TabbozStartNet(HANDLE hDlg)
{
char tmp[255];
int iSndSize;
net_enable=1;
sprintf(lastconnect,"none");
/*Initialize the winsock.dll*/
status = WSAStartup(0x101, &Data);
if (status != 0) {
MessageBox( hDlg,
"La funzione WSAStartup non e' andata a buon fine...\nLe funzioni di rete del Tabboz Simulator verranno disabilitate...", "Network Startup", MB_OK | MB_ICONHAND);
#ifdef TABBOZ_DEBUG
neterrorlog("ERROR: WSAStartup Unsuccessful");
#endif
net_enable=0;
return;
}
#ifdef TABBOZ_DEBUG
writelog("net: WSAStart() is OK");
sprintf(tmp, "net: Windows Sockets = %-40s",Data.szDescription); writelog(tmp);
sprintf(tmp, "net: System status = %-40s",Data.szSystemStatus);writelog(tmp);
sprintf(tmp, "net: Vendor info = %-40s",Data.lpVendorInfo); writelog(tmp);
sprintf(tmp, "net: Winsock version = %04x",Data.wVersion); writelog(tmp);
sprintf(tmp, "net: Max Sockets = %d",Data.iMaxSockets); writelog(tmp);
sprintf(tmp, "net: Max Datagram = %d",Data.iMaxUdpDg); writelog(tmp);
#endif
#define INUTILE
#ifdef INUTILE
{
char szLocalHostName[MAXHOSTNAMELEN];
LPHOSTENT lpheHostEnt;
/* Get the local host name and save it */
if (gethostname((LPSTR)szLocalHostName, sizeof(szLocalHostName)) == SOCKET_ERROR)
{
lstrcpy((LPSTR) szLocalHostName, (LPSTR) STRING_UNKNOWN);
} else {
lpheHostEnt = gethostbyname((LPSTR)szLocalHostName);
if (lpheHostEnt != NULL)
{
lstrcpy((LPSTR) szLocalHostName, lpheHostEnt->h_name);
}
}
sprintf(tmp, "net: Hostname = %s",szLocalHostName); writelog(tmp);
}
#endif
/* Zero the sockaddr in structure */
memset(&serverSockAddr, 0, sizeof(serverSockAddr));
/* Specify the port portion of the address */
serverSockAddr.sin_port = htons(PortNumber);
/* SPecify family */
serverSockAddr.sin_family = AF_INET;
serverSockAddr.sin_addr.s_addr = htonl(INADDR_ANY);
/* Create the socket */
#ifdef TABBOZ_DEBUG
writelog("net: Starting the Server.....");
#endif
serverSocket = socket(AF_INET, SOCK_STREAM, 0);
if (serverSocket == INVALID_SOCKET)
{
#ifdef TABBOZ_DEBUG
neterrorlog("ERROR: Socket Unsuccessful");
#endif
status = WSACleanup();
if (status == SOCKET_ERROR)
{
#ifdef TABBOZ_DEBUG
neterrorlog("ERROR: WSA CLeanup Unsuccessful");
#endif
}
net_enable=0;
return;
} /* end if serverSocket */
/* Associate the Socket with the address */
status = bind(serverSocket, (LPSOCKADDR) &serverSockAddr, sizeof(serverSockAddr));
if (status == SOCKET_ERROR)
{
#ifdef TABBOZ_DEBUG
neterrorlog("ERROR: Bind Unsuccessful");
net_enable=0;
return;
#endif
}
/* Start to listen to connections */
status = listen(serverSocket, 1);
if (status == SOCKET_ERROR)
{
#ifdef TABBOZ_DEBUG
neterrorlog("ERROR: Listen Unsuccessful");
net_enable=0;
return;
#endif
}
#ifdef TABBOZ_DEBUG
sprintf(tmp,"net: Tabboz Simulator Listening on Port %d",PortNumber);
writelog(tmp);
#endif
if ( WSAAsyncSelect(serverSocket, hDlg, SOCKET_MESSAGE, FD_ACCEPT) == SOCKET_ERROR )
{
#ifdef TABBOZ_DEBUG
neterrorlog("ERROR: select() Unsuccessful");
#endif
closesocket(serverSocket);
net_enable=0;
return;
}
iSndSize = 1024;
if ( setsockopt(serverSocket, SOL_SOCKET, SO_SNDBUF, (char FAR *) &iSndSize, sizeof(iSndSize)) == SOCKET_ERROR) {
#ifdef TABBOZ_DEBUG
neterrorlog("Error setting socket SO_SNDBUF");
#endif
}
sprintf(lastneterror,"Network Server is Running");
} /* End TabbozStartNet */
/**************************************************************/
/**************************************************************/
void SendReceiveToClient(void *cs)
{
char buffer[MAXBUFLEN];
int status;
int numsnt;
int numrcv;
int ctr = 0;
char sent[1024];
char tmp[255];
char finished[] = "The task has been finished!\n";
char unfinished[] = "Not finished yet!!!\n";
SOCKET clientSocket = (SOCKET)cs;
sprintf(sent,"Tabboz Simulator %s %s\n\r\n\r"
"Nome: [%s %s] Soldi: [%s] Sesso: [%c]\n\r"
"Fig: [%03d] Rep: [%03d] Prof.Scol.: [%03d]\n\r"
,VERSION,__DATE__, Nome, sesso, Cognome,MostraSoldi(Soldi),Fama,Reputazione,Studio);
if ( Rapporti != 0 ) {
if (sesso == 'M')
sprintf(tmp, "Tipa: [%s] Rap: [%03d]\n\r",Nometipa,Rapporti);
else
sprintf(tmp, "Tipo: [%s] Rap: [%03d]\n\r",Nometipa,Rapporti);
strcat(sent,tmp);
}
if (ScooterData.stato != -1) {
sprintf(tmp, "Scooter: [%s] Stato: [%03d]\n\r",ScooterData.nome,ScooterData.stato);
strcat(sent,tmp);
}
numsnt = send(clientSocket,sent,strlen(sent)+1,NO_FLAGS_SET);
// sprintf(sent, "\n\r%s %d %s",InfoSettimana[x_giornoset-1].nome,x_giorno,InfoMese[x_mese-1].nome); strcat(sent,tmp);
// numsnt = send(clientSocket,sent,strlen(sent)+1,NO_FLAGS_SET);
status = shutdown(clientSocket, 2);
if (status == SOCKET_ERROR)
{
#ifdef TABBOZ_DEBUG
writelog("net: ERROR: Shutdown Unsuccessful");
#endif
}
/* Close Socket */
status = closesocket(clientSocket);
if (status == SOCKET_ERROR)
{
#ifdef TABBOZ_DEBUG
writelog("net: ERROR: Close Socket Unsuccessful");
#endif
}
return;
/*
while(1)
{
numrcv = recv(clientSocket,buffer, MAXBUFLEN, NO_FLAGS_SET);
if ((numrcv == 0) || (numrcv == SOCKET_ERROR))
{
printf("\n Connection Terminated \n");
break;
}
ctr=1;
if (ctr == 1)
{
strcpy(sent,finished);
printf("\n Done \n");
printf("\n Sending back to Client the message => %s",sent);
numsnt = send(clientSocket,sent,strlen(sent)+1,NO_FLAGS_SET);
status = shutdown(clientSocket, 2);
if (status == SOCKET_ERROR)
{
printf("\n ERROR: Shutdown Unsucessful\n");
}
// close Socket
status = closesocket(clientSocket);
if (status == SOCKET_ERROR)
{
printf("\n ERROR: Close Socket Unsuccessful \n");
}
}
ctr++;
}
printf("\n The Java Client's message is => %s", &buffer);
transferData(buffer);
*/
}
/**************************************************************/
void transferData(char newbuf[])
{
char str1,str2,str3;
int angle1,angle2,angle3;
int dirstr1,dirstr2,dirstr3;
sscanf(newbuf,"%c %d %d %c %d %d %c %d %d",&str1,&dirstr1,&angle1,
&str2,&dirstr2,&angle2,&str3,&dirstr3,&angle3);
printf("\n str1 : %c",str1);
}
/**************************************************************/
/* Network Config / Stat [25 Giugno 1998] */
/**************************************************************/
# pragma argsused
BOOL FAR PASCAL Network(HWND hDlg, WORD message, WORD wParam, LONG lParam)
{
char tmp[1024];
static int net_temp_status;
static int temp_PortNumber;
if (message == WM_INITDIALOG) {
net_temp_status=net_enable;
temp_PortNumber=PortNumber;
if (Data.wVersion != 0) {
sprintf(tmp, "%s",Data.szDescription); SetDlgItemText(hDlg, 101, tmp);
sprintf(tmp, "%s",Data.szSystemStatus); SetDlgItemText(hDlg, 102, tmp);
sprintf(tmp, "%04x",Data.wVersion); SetDlgItemText(hDlg, 103, tmp);
} else {
sprintf(tmp, "");
SetDlgItemText(hDlg, 101, tmp);
SetDlgItemText(hDlg, 102, tmp);
SetDlgItemText(hDlg, 103, tmp);
}
sprintf(tmp, "%s",lastconnect); SetDlgItemText(hDlg, 104, tmp);
sprintf(tmp, "%d",PortNumber); SetDlgItemText(hDlg, 105, tmp);
SetFocus(GetDlgItem(hDlg, 105));
if (net_enable)
SendMessage(GetDlgItem(hDlg, 106), BM_SETCHECK, TRUE, 0L);
sprintf(tmp, "%s",lastneterror); SetDlgItemText(hDlg, 107, tmp);
return(TRUE);
} else if (message == WM_COMMAND) {
switch (wParam)
{
case 105:
GetDlgItemText(hDlg, wParam, tmp, sizeof(tmp));
temp_PortNumber=atoi(tmp);
if (temp_PortNumber == 0) temp_PortNumber=79;
return(TRUE);
case 106:
net_temp_status=!net_temp_status;
return(TRUE);
case IDCANCEL:
EndDialog(hDlg, TRUE);
return(TRUE);
case IDOK:
if (net_temp_status != net_enable) {
net_enable=net_temp_status;
if (net_enable) {
/* Attiva il server... */
TabbozStartNet(NEThDlg);
} else {
/* Disattiva il server... */
closesocket(serverSocket);
WSACleanup();
#ifdef TABBOZ_DEBUG
writelog("net: Tabboz Simulator Server is going down...");
sprintf(lastneterror,"Network Server is Down");
#endif
}
}
if (PortNumber != temp_PortNumber) {
PortNumber=temp_PortNumber;
if (net_enable) {
/* Disattiva il server... */
closesocket(serverSocket);
WSACleanup();
#ifdef TABBOZ_DEBUG
writelog("net: Tabboz Simulator Server is going down...");
#endif
/* Riattiva il server... */
TabbozStartNet(NEThDlg);
}
}
EndDialog(hDlg, TRUE);
return(TRUE);
default:
return(TRUE);
}
}
return(FALSE);
}
/**************************************************************/
void neterrorlog(char *s)
{
char tmp[255];
sprintf(lastneterror,"%s",s);
#ifdef TABBOZ_DEBUG
sprintf(tmp,"net: %s",s);
writelog(tmp);
#endif
}
/**************************************************************/
#endif /* NONETWORK */
#endif
| [
"[email protected]"
] |
Subsets and Splits