Ejemplo n.º 1
0
int linuxAudioOutPCM(FskAudioOut audioOut, char *p, int size) {
	FskErr err = kFskErrNone;
	FskAudioOutBlock audioBlock;
	androidAudioExt *ext = (androidAudioExt*)audioOut->ext;
	int wrote = 0, remains = 0;
int origSize = size;

	if (NULL == audioOut->blocks->list)
		goto bail;

	if (0 != FskMutexTrylock(audioOut->blocks->mutex)) {
		FskMutexAcquire(audioOut->blocks->mutex);
	}
//FskAudioNativePrintfDebug("before FskListMutex - grabbed blocks %x (blocks)", audioOut->blocks);
	while (size) {
		char *pos;
		audioBlock = (FskAudioOutBlock)audioOut->blocks->list;
		while (audioBlock && audioBlock->done)
{
			audioBlock = audioBlock->next;
}
		if (!audioBlock) {
			if (0 == ext->bytesEnqueued) {
				FskAudioNativePrintfMinimal("no more free PCM blocks to play");
				FskAudioNativePrintfMinimal(" - there are %u bytes enqueued - wanted %d (orig size %d)", (unsigned)ext->bytesEnqueued, size, origSize);
			}
			goto bail;
		}

		if (audioBlock->loc)		// remainder
			 pos = audioBlock->loc;
		else
			 pos = (char*)audioBlock->data;

		if (audioBlock->dataSize <= (unsigned)size) {
			FskMemCopy(p, pos, audioBlock->dataSize);
			wrote += audioBlock->dataSize;
			p += audioBlock->dataSize;
			size -= audioBlock->dataSize;
			ext->bytesEnqueued -= audioBlock->dataSize;
audioBlock->dataSize = 0;	// only setting this for a debug message
			audioBlock->done = true;
			continue;
		}
		else {
			FskMemCopy(p, pos, size);
			wrote += size;
			audioBlock->loc = pos + size;
			audioBlock->dataSize -= size;
			FskAudioNativePrintfDebug("Consuming %d bytes (block left: %d) (total left %d)", size, audioBlock->dataSize, ext->bytesEnqueued - size);
			ext->bytesEnqueued -= size;
			size = 0;
			break;
		}
	}
bail:
	FskMutexRelease(audioOut->blocks->mutex);

	return wrote;
}
Ejemplo n.º 2
0
FskErr FskUUIDCreate(FskUUID uuid)
{
	FskTimeRecord time;
	static UInt32 clockSequence = 0;
	static FskTimeRecord lastTime;
	char MAC[6];
	FskNetInterfaceRecord *netInterface = NULL;
	UInt32 numInterfaces;

	// find a suitable network interface to get the MAC address from
	numInterfaces = FskNetInterfaceEnumerate();

	while (numInterfaces--) {
		FskNetInterfaceDescribe(numInterfaces, &netInterface);
		if ((0 == netInterface->MAC[0]) && (0 == netInterface->MAC[1]) && (0 == netInterface->MAC[2]) &&
			(0 == netInterface->MAC[3]) && (0 == netInterface->MAC[4]) && (0 == netInterface->MAC[5])) {
			FskNetInterfaceDescriptionDispose(netInterface);
			netInterface = NULL;
			continue;
		}
		break;
	}

	if (NULL == netInterface) {
		// can't fail - clients need a value. make something up. (this happens if all network interfaces are disabled on a phone)
		int i;
		for (i = 0; i < 6; i++)
			MAC[i] = (char)FskRandom();
	}
	else {
		FskMemMove(MAC, netInterface->MAC, sizeof(netInterface->MAC));
		FskNetInterfaceDescriptionDispose(netInterface);
	}

	// make sure the clock sequence is good
	while (0 == clockSequence)
		clockSequence = FskRandom();

	// we need the time, and make sure it is unique.
	FskTimeGetNow(&time);                                           //@@ should be UTC time
	time.useconds = (time.useconds >> 4) | (time.seconds << 28);	// only uses 60 bits of time
	time.seconds >>= 4;												// only uses 60 bits of time
	if (FskTimeCompare(&time, &lastTime) <= 0)
		clockSequence += 1;

	lastTime = time;

	// put the pieces together
	time.useconds = FskEndianU32_NtoB(time.useconds);
	FskMemCopy(&uuid->value[0], &time.useconds, sizeof(time.useconds));
	uuid->value[4] = (UInt8)time.seconds;
	uuid->value[5] = (UInt8)(time.seconds >> 8);
	uuid->value[6] = (((UInt8)(time.seconds >> 24)) & 0x0f) | 1;
	uuid->value[7] = (UInt8)(time.seconds >> 16);
	uuid->value[8] = ((UInt8)(clockSequence >> 8) & 0x3f) | 0x80;
	uuid->value[9] = (UInt8)clockSequence;
	FskMemCopy(&uuid->value[10], MAC, sizeof(MAC));

	return kFskErrNone;
}
Ejemplo n.º 3
0
FskErr KprAuthorityReverse(char* id, char** di)
{
	FskErr err = kFskErrNone;
	char *p, *q;
	SInt32 c = FskStrLen(id), i;
	bailIfError(FskMemPtrNew(c + 1, di));
	p = id + c;
	q = *di;
	i = 0;
	while (c) {
		c--;
		p--;
		if (*p == '.') {
			p++;
			FskMemCopy(q, p, i);
			q += i;
			*q++ = '.';
			p--;
			i = 0;
		}
		else
			i++;
	}
	FskMemCopy(q, p, i);
	q += i;
	*q = 0;
bail:
	return err;
}
Ejemplo n.º 4
0
FskErr
FskSSLWrite(void *a, const void *buf, int *bufLen)
{
	FskSSL *fssl = a;
	FskErr err = kFskErrNone;
	int len = *bufLen;

	if (fssl->skt == NULL)
		return kFskErrOperationFailed;

	if (buf == NULL || len == 0)
		return kFskErrNone;

	xsBeginHost(fssl->vm->the);
	xsTry {
		xsVars(1);
		xsCall1_noResult(fssl->socket, xsID("attachData"), xsHostData(fssl->skt));
		xsVar(0) = xsNew1(xsGlobal, xsID("Chunk"), xsInteger(len));
		FskMemCopy(xsGetHostData(xsVar(0)), buf, len);
		xsResult = xsCall2(fssl->ssl, xsID("write"), fssl->socket, xsVar(0));
		*bufLen = xsToInteger(xsResult);
		if (*bufLen == 0)
			err = kFskErrNoData;
		xsCall0_noResult(xsVar(0), xsID("free"));
	}  xsCatch {
		if (xsHas(xsException, xsID("code")))
			err = xsToInteger(xsGet(xsException, xsID("code")));
		if (err == kFskErrNone)
			err = kFskErrOperationFailed;
	}
	xsEndHost(fssl->vm->the);
	return err;
}
Ejemplo n.º 5
0
static FskErr KprWebSocketEndpointStartClosingHandshake(KprWebSocketEndpoint self, UInt16 code, char *reason)
{
	FskErr err = kFskErrNone;
	char *payload = NULL;
	UInt32 length = sizeof(UInt16);
	
	self->state = kKprWebSocketStateClosing;
	CALLBACK(closingCallback)(self, self->closeCode, self->closeReason, self->cleanClose, self->refcon);

	length += FskStrLen(reason);
	bailIfError(FskMemPtrNew(length, &payload));
	
	*((UInt16 *) payload) = FskEndianU16_NtoB(code);
	FskMemCopy(&payload[2], reason, length - sizeof(UInt16));
	
	bailIfError(KprWebSocketEndpointSendRawFrame(self, kKprWebSocketOpcodeClose, payload, length));
	self->closeWasSent = true;
	
bail:
	if (payload) FskMemPtrDispose(payload);
	
	if (err || (self->closeWasSent && self->closeWasReceived)) {
		self->cleanClose = (err == kFskErrNone);
		KprWebSocketEndpointDisconnect(self);
	}
	
	return err;
}
Ejemplo n.º 6
0
FskErr FskHTTPServerRequestGetStats(FskHTTPServerRequest request, FskHTTPServerRequestStatsRecord *stats) {
	if (request)
		FskMemCopy(stats, &request->stats, sizeof(request->stats));
	else
		return kFskErrParameterError;
	return kFskErrNone;
}
Ejemplo n.º 7
0
FskErr
FskSSLRead(void *a, void *buf, int *bufLen)
{
	FskSSL *fssl = a;
	FskErr err = kFskErrNone;
	int len = *bufLen, nread;

	if (fssl->skt == NULL)
		return kFskErrOperationFailed;

	xsBeginHost(fssl->vm->the);
	xsTry {
		xsCall1_noResult(fssl->socket, xsID("attachData"), xsHostData(fssl->skt));
		xsResult = xsCall2(fssl->ssl, xsID("read"), fssl->socket, xsInteger(len));
		if (xsTest(xsResult)) {
			nread = xsToInteger(xsGet(xsResult, xsID("length")));
			if (nread > len)
				nread = len;
			FskMemCopy(buf, xsGetHostData(xsResult), nread);
			xsCall0_noResult(xsResult, xsID("free"));
			*bufLen = nread;
			err = nread == 0 ? kFskErrNoData: kFskErrNone;
		}
		else
			err = kFskErrConnectionClosed;
	} xsCatch {
		if (xsHas(xsException, xsID("code")))
			err = xsToInteger(xsGet(xsException, xsID("code")));
		if (err == kFskErrNone)
			err = kFskErrOperationFailed;
	}
	xsEndHost(fssl->vm->the);
	return err;
}
Ejemplo n.º 8
0
static FskErr KprWebSocketEndpointCreateFrame(Boolean fin, UInt8 opcode, Boolean mask, void *payload, UInt32 length, void **frame, UInt32 *frameLength)
{
	FskErr err = kFskErrNone;
	UInt8 headers[14], maskData[4];
	UInt32 headerLen = 1 + 1;
	
	headers[0] = opcode;
	if (fin) {
		headers[0] |= 0x80u;
	}
	
	if (length < 126) {
		headers[1] = (UInt8) length;
	} else if (length < 0x10000l) {
		headers[1] = 126;
		
		*((UInt16 *)&headers[2]) = FskEndianU16_NtoB(length);
		headerLen += sizeof(UInt16);
	} else {
		headers[1] = 127;
		
		*((FskInt64 *)&headers[2]) = FskEndianU64_NtoB(length);
		headerLen += sizeof(FskInt64);
	}
	
	if (mask) {
		headers[1] |= 0x80u;
		
		*((SInt32 *)maskData) = FskRandom();
		FskMemCopy(&headers[headerLen], maskData, sizeof(maskData));
		headerLen += sizeof(UInt32);
	}
	
	bailIfError(FskMemPtrNew(headerLen + length, frame));
	FskMemCopy(*frame, headers, headerLen);
	if (length > 0) {
		FskMemCopy((UInt8 *) *frame + headerLen, payload, length);
	}
	*frameLength = headerLen + length;
	
	if (mask) {
		KprWebSocketMask((UInt8 *) *frame + headerLen, length, maskData);
	}
	
bail:
	return err;
}
Ejemplo n.º 9
0
FskErr FskHTTPServerGetStats(FskHTTPServer http, FskHTTPServerStats *stats) {

	if (http)
		FskMemCopy(stats, &http->stats, sizeof(http->stats));
	else
		return kFskErrParameterError;
	return kFskErrNone;
}
Ejemplo n.º 10
0
void KPR_system_getWifiInfo(xsMachine* the)
{
    DWORD dwResult = 0;
    HANDLE hClient = NULL;
    DWORD dwMaxClient = 2; 
    DWORD dwCurVersion = 0;
    PWLAN_INTERFACE_INFO_LIST pIfList = NULL;
    int i;
    PWLAN_INTERFACE_INFO pIfInfo = NULL;
    DWORD connectInfoSize = sizeof(WLAN_CONNECTION_ATTRIBUTES);
    PWLAN_CONNECTION_ATTRIBUTES pConnectInfo = NULL;
    WLAN_OPCODE_VALUE_TYPE opCode = wlan_opcode_value_type_invalid;
    ULONG length;
	xsVars(1);
    dwResult = WlanOpenHandle(dwMaxClient, NULL, &dwCurVersion, &hClient); 
    if (dwResult != ERROR_SUCCESS) 
    	goto bail;
	dwResult = WlanEnumInterfaces(hClient, NULL, &pIfList); 
    if (dwResult != ERROR_SUCCESS)
    	goto bail;
    for (i = 0; i < (int) pIfList->dwNumberOfItems; i++) {
		pIfInfo = (WLAN_INTERFACE_INFO *) &pIfList->InterfaceInfo[i];
   		if (pIfInfo->isState == wlan_interface_state_connected) {
			dwResult = WlanQueryInterface(hClient, &pIfInfo->InterfaceGuid,
										  wlan_intf_opcode_current_connection,
										  NULL,
										  &connectInfoSize,
										  (PVOID *) &pConnectInfo, 
										  &opCode);
			if (dwResult != ERROR_SUCCESS)
				goto bail;
			length = pConnectInfo->wlanAssociationAttributes.dot11Ssid.uSSIDLength;
			if (length > 0) {
				xsResult = xsNewInstanceOf(xsObjectPrototype);
				xsVar(0) = xsStringBuffer(NULL, length + 1);
				FskMemCopy(xsToString(xsVar(0)), pConnectInfo->wlanAssociationAttributes.dot11Ssid.ucSSID, length);
				xsSet(xsResult, xsID("SSID"), xsVar(0));
			}
   			break;
   		}
   	}
bail:
    if (pConnectInfo != NULL) {
        WlanFreeMemory(pConnectInfo);
        pConnectInfo = NULL;
    }
    if (pIfList != NULL) {
        WlanFreeMemory(pIfList);
        pIfList = NULL;
    }
    if (hClient != NULL) {
        WlanCloseHandle(hClient, NULL);
        hClient = NULL;
    }
}
Ejemplo n.º 11
0
FskErr
FskSSLLoadCerts(void *a, FskSocketCertificateRecord *cert)
{
	FskSSL *fssl = a;
	FskErr err = kFskErrNone;

	xsBeginHost(fssl->vm->the);

	xsTry {
		xsVars(2);

		xsVar(0) = xsUndefined;
		xsVar(1) = xsUndefined;
		if (cert != NULL) {
			if (cert->certificates != NULL && cert->certificatesSize > 0) {
				xsVar(0) = xsNew1(xsGlobal, xsID("Chunk"), xsInteger(cert->certificatesSize));
				FskMemCopy(xsGetHostData(xsVar(0)), cert->certificates, cert->certificatesSize);
			}
			if (cert->policies != NULL) {
				if (cert->certificates == NULL)
					xsVar(0) = xsNew0(xsGlobal, xsID("Chunk"));	// create a null chunk just for setting the polices
				xsSet(xsVar(0), xsID("policies"), xsString(cert->policies));
			}
			if (cert->hostname != NULL) {
				xsSet(fssl->socket, xsID("hostname"), xsString(cert->hostname));	// too easy but should work...
			}
			if (cert->key != NULL && cert->keySize > 0) {
				xsVar(1) = xsNew1(xsGlobal, xsID("Chunk"), xsInteger(cert->keySize));
				FskMemCopy(xsGetHostData(xsVar(1)), cert->key, cert->keySize);
			}
		}
		xsCall2_noResult(fssl->ssl, xsID("loadCerts"), xsVar(0), xsVar(1));
	} xsCatch {
		if (xsHas(xsException, xsID("code")))
			err = xsToInteger(xsGet(xsException, xsID("code")));
		if (err == kFskErrNone)
			err = kFskErrOperationFailed;
	}

	xsEndHost(fssl->vm->the);
	return err;
}
Ejemplo n.º 12
0
void KPR_message_get_responseChunk(xsMachine *the)
{
	KprMessage self = xsGetHostData(xsThis);
	void* data;
	UInt32 size; 
	KprMessageGetResponseBody(self, &data, &size);
	if (data && size) {
		xsResult = xsNew1(xsGlobal, xsID_Chunk, xsInteger(size));
		FskMemCopy(xsGetHostData(xsResult), data, size);
	}
}
Ejemplo n.º 13
0
FskErr KprMemoryBufferNewFromData(UInt32 size, void *buffer, KprMemoryBuffer *it)
{
	FskErr err;
	KprMemoryBuffer self;

	bailIfError(KprMemoryBufferNew(size, &self));
	FskMemCopy(self->buffer, buffer, size);
	*it = self;

bail:
	return err;
}
Ejemplo n.º 14
0
void fxLink(txMachine* the, xsGrammar* theGrammar)
{
	txScript* script = NULL;
	FskErr err = kFskErrNone;
	err = FskMemPtrNewClear(sizeof(txScript), &script);
	if (err) goto bail;
	err = FskMemPtrNew(theGrammar->symbolsSize, &script->symbolsBuffer);
	if (err) goto bail;
	err = FskMemPtrNew(theGrammar->codeSize, &script->codeBuffer);
	if (err) goto bail;
	FskMemCopy(script->symbolsBuffer, theGrammar->symbols, theGrammar->symbolsSize);
	script->symbolsSize = theGrammar->symbolsSize;
	FskMemCopy(script->codeBuffer, theGrammar->code, theGrammar->codeSize);
	script->codeSize = theGrammar->codeSize;
	script->callback = theGrammar->callback;
	fxRunScript(the, script, C_NULL, C_NULL, C_NULL, C_NULL);
	script = C_NULL;
bail:
	fxDeleteScript(script);
	return;
}
Ejemplo n.º 15
0
FskErr KplNetInterfaceEnumerate(KplNetInterfaceRecord **interfaceList)
{
	FskErr err = kFskErrNone;
	KplNetInterfaceRecord *nir;
	struct ifaddrs* ifaddr = NULL;
	struct ifaddrs* ifa;
	int fd = -1;
	struct ifreq  ifr;
    
	*interfaceList = NULL;

	if (getifaddrs(&ifaddr) == -1) {
		err = kFskErrNetworkInterfaceError;
		goto done;
	}
	
	fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP);
	if (fd < 0) goto done;
    
	for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) {
		if (ifa->ifa_addr == NULL)
			continue;

		if (ifa->ifa_addr->sa_family == AF_INET) {
			memset(&ifr, 0,  sizeof(struct ifreq));
			strncpy(ifr.ifr_name, ifa->ifa_name, IFNAMSIZ);
			ifr.ifr_name[IFNAMSIZ - 1] = 0;
            
			FskMemPtrNewClear(sizeof(KplNetInterfaceRecord), (FskMemPtr *)&nir);
			if (!nir) {
				err = kFskErrMemFull;
				goto done;
			}
			nir->name = FskStrDoCopy(ifa->ifa_name);
			nir->ip = ntohl(((struct sockaddr_in *)ifa->ifa_addr)->sin_addr.s_addr);
			nir->netmask = ntohl(((struct sockaddr_in *)ifa->ifa_netmask)->sin_addr.s_addr);
			nir->status = (ifa->ifa_flags & IFF_UP) ? 1 : 0;
			if (ioctl(fd, SIOCGIFHWADDR, &ifr) >= 0) {
				if (ifr.ifr_hwaddr.sa_family == ARPHRD_ETHER) {
					FskMemCopy(nir->MAC, ifr.ifr_hwaddr.sa_data, 6);
				}
			}
			FskListAppend((FskList*)interfaceList, nir);
		}
	}
    
done:
	if (fd >= 0)
		close(fd);
	if (ifaddr)
		freeifaddrs(ifaddr);
	return err;
}
Ejemplo n.º 16
0
void KPR_message_get_requestChunk(xsMachine *the)
{
	KprMessage self = xsGetHostData(xsThis);
	void* data;
	UInt32 size; 
	KprMessageGetRequestBody(self, &data, &size);
// 	xsTrace("message.requestChunk deprecated, use requestBuffer\n");
	if (data && size) {
		xsResult = xsNew1(xsGlobal, xsID_Chunk, xsInteger(size));
		FskMemCopy(xsGetHostData(xsResult), data, size);
	}
}
Ejemplo n.º 17
0
FskErr KprMemoryBufferNewFromString(const char *str, KprMemoryBuffer *it)
{
	FskErr err;
	KprMemoryBuffer self;
	UInt32 size = FskStrLen(str);

	bailIfError(KprMemoryBufferNew(size, &self));
	FskMemCopy(self->buffer, str, size);
	*it = self;

bail:
	return err;
}
Ejemplo n.º 18
0
FskErr KprMessageSetResponseBody(KprMessage self, void* data, UInt32 size)
{
	FskErr err = kFskErrNone;
	FskMemPtrDisposeAt(&self->response.body);
	self->response.size = 0;
	if (data && size) {
		bailIfError(FskMemPtrNew(size, &self->response.body));
		FskMemCopy(self->response.body, data, size);
		self->response.size = size;
	}
bail:
	return err;
}
Ejemplo n.º 19
0
FskErr KprMessageSetRequestCertificate(KprMessage self, void* certificate, UInt32 size, char *policies)
{
	FskErr err = kFskErrNone;
	FskMemPtrDisposeAt(&self->request.certificate);
	FskMemPtrDisposeAt(&self->request.policies);
	self->request.certificateSize = 0;
	if (certificate && size) {
		bailIfError(FskMemPtrNew(size, &self->request.certificate));
		FskMemCopy(self->request.certificate, certificate, size);
		self->request.certificateSize = size;
	}
	self->request.policies = FskStrDoCopy(policies);
bail:
	return err;
}
Ejemplo n.º 20
0
static FskErr KprWebSocketEndpointHandleTextMessage(KprWebSocketEndpoint self, void *message, UInt32 length)
{
	FskErr err = kFskErrNone;
	char *text = NULL;

	bailIfError(FskMemPtrNew(length + 1, &text));
	FskMemCopy(text, message, length);
	text[length] = 0;

	CALLBACK(textCallback)(self, text, self->refcon);

bail:
	if (text) FskMemPtrDispose(text);
	return err;
}
Ejemplo n.º 21
0
void on_drag_data_received(GtkWidget* widget, GdkDragContext* context, gint x, gint y, GtkSelectionData *data, guint info, guint time, gpointer user_data)
{
	FskGtkWindow gtkWin = user_data;
	gboolean dnd_success = FALSE;
	FskDragDropFile dropFileList = NULL;
	FskDragDropFile droppedFile = NULL;
	char* path = NULL;
	if (gdk_drag_context_get_suggested_action(context) == GDK_ACTION_COPY) {
		char* string = (char*)gtk_selection_data_get_data(data);
		char* end;
		FskFileInfo itemInfo;
		for (end = FskStrStr(string, "\r\n"); end; end = FskStrStr(string, "\r\n")) {
			BAIL_IF_ERR(FskMemPtrNewClear(sizeof(FskDragDropFileRecord), (FskMemPtr*)&droppedFile));
			FskListAppend((FskList *)&dropFileList, droppedFile);
			*end = 0;
			BAIL_IF_ERR(KprURLToPath(string, &path));
			BAIL_IF_ERR(FskFileGetFileInfo(path, &itemInfo));
			if (itemInfo.filetype == kFskDirectoryItemIsDirectory) {
				int length = FskStrLen(path);
				BAIL_IF_ERR(FskMemPtrNew(length + 2, &droppedFile->fullPathName));
				FskMemCopy(droppedFile->fullPathName, path, length);
				droppedFile->fullPathName[length] = '/';
				droppedFile->fullPathName[length + 1] = 0;
				FskMemPtrDispose(path);
			}
			else {
				droppedFile->fullPathName = path;
			}
			path = NULL;
			string = end + 2;
			*end = '\r';
		}
		(*gDropTargetProc)(kFskDragDropTargetEnterWindow, x, y, dropFileList, gtkWin->owner);
		(*gDropTargetProc)(kFskDragDropTargetDropInWindow, x, y, dropFileList, gtkWin->owner);
		dnd_success = TRUE;
	}
bail:
	gtk_drag_finish(context, dnd_success, TRUE, time);
	FskMemPtrDispose(path);
	while (NULL != dropFileList) {
		droppedFile = dropFileList;
		FskListRemove((FskList *)&dropFileList, droppedFile);
		FskMemPtrDispose(droppedFile->fullPathName);
		FskMemPtrDispose(droppedFile);
	}
}
Ejemplo n.º 22
0
// scanProcMount
void scanProcMount() {
	FskErr err;
	FILE *mntFile = NULL;
	char *mntFileBuffer;
	int bufEnd = 0;
	int done = 0;
	int amt;
	char *bufPos, *lineEnd, *path;
	extMount ext = NULL;
	fstabDesc fsDesc = NULL;

	// the default
	addVolume(gAndroidCallbacks->getStaticDataDirCB(), kFskVolumeTypeFixed, 0);
	// and the Jellybean user-space
	addVolume(gAndroidCallbacks->getStaticExternalDirCB(), kFskVolumeTypeSDMemory, 0);

	// read mount file
	err = FskMemPtrNew(MOUNT_BUF_SIZE+1, &mntFileBuffer);
	BAIL_IF_ERR(err);
	bufPos = mntFileBuffer;

	mntFile = FOPEN(LINUX_MOUNT_FILE, "r");
	if (NULL == mntFile) {
		FskAndroidFilesPrintfDebug("opening %s - %d\n", LINUX_MOUNT_FILE, errno);
		return;
	}

	while (!done) {
		// fill the buffer
		amt = fread(mntFileBuffer + bufEnd, 1, MOUNT_BUF_SIZE - bufEnd, mntFile);
		mntFileBuffer[bufEnd + amt + 1] = '\0';

		FskAndroidFilesPrintfDebug("fread %x, %d - got %d\n", mntFileBuffer + bufEnd, MOUNT_BUF_SIZE - bufEnd, amt);
		if (amt > 0)
			bufEnd += amt;
		FskAndroidFilesPrintfDebug("check while(bufpos...) - %p < %p (%d left)\n", bufPos, mntFileBuffer + bufEnd, mntFileBuffer+bufEnd - bufPos);
		while (bufPos < mntFileBuffer + bufEnd) {
			char fsName[256], fsMnt[256], fsType[32];

			// until we have a full line
			if (NULL == (lineEnd = FskStrChr(bufPos, kFskLF)))
				break;

			bufPos = FskStrNCopyUntilSpace(fsName, bufPos, 255);
			bufPos = FskStrNCopyUntilSpace(fsMnt, bufPos, 255);
			bufPos = FskStrNCopyUntilSpace(fsType, bufPos, 31);
			FskAndroidFilesPrintfDebug("got Name: %s Mnt: %s Type: %s\n", fsName, fsMnt, fsType);

			path = fsMnt;
			if ((ext = extMountsContain(path))) {
				FskAndroidFilesPrintfDebug("found path in external mounts %s\n", path);
				fsDesc = extMountToType(ext);
				if (fsDesc)
					addVolume(path, fsDesc->type, fsDesc->removable);
				else
					addVolume(path, kFskVolumeTypeSDMemory, 1);
				goto nextLine;
			}
			FskAndroidFilesPrintfDebug(" - didn't find path in external mounts %s\n", path);

			if (0 == FskStrCompare(fsType, "vfat") || 0 == FskStrCompare(fsType, "fuse")) {
				if (0 != FskStrStr(fsMnt, "emulated")) {
					FskAndroidFilesPrintfDebug(" - emulated - ignore\n");
					goto nextLine;
				}
				path = fsMnt;
				FskAndroidFilesPrintfDebug(" - got a vfat (or fuse) - path is %s\n", path);
				if (0 == FskStrStr(path, "/asec")) {
					FskAndroidFilesPrintfDebug(" - vfat without asec: %s\n", path);
					addVolume(path, kFskVolumeTypeSDMemory, 1);
				}
				else {
					FskAndroidFilesPrintfDebug(" - vfat with asec - ignore - %s\n", path);
				}
			}
nextLine:
			bufPos = lineEnd + 1;
		}

		if (amt == 0) {	// we read no more
			done = 1;
		}
		else {
			// push buffer to beginning
			amt = (mntFileBuffer + bufEnd) - bufPos;
			FskAndroidFilesPrintfDebug("push unread %d bytes to beginning of buffer\n - mntFileBuffer: %d  bufEnd: %d  bufPos: %d\n", amt, mntFileBuffer, bufEnd, bufPos);
			if (amt > 0)
				FskMemCopy(mntFileBuffer, bufPos, amt);
			bufPos = mntFileBuffer;
			bufEnd -= amt;
		}
	}

bail:
	if (NULL != mntFile)
		fclose(mntFile);
}
Ejemplo n.º 23
0
FskErr KplNetInterfaceEnumerate(KplNetInterfaceRecord **interfaceList)
{
	FskErr err = kFskErrNone;
	KplNetInterfaceRecord *nir;
	int fd;
	struct ifreq ifr;
	struct sockaddr_in *sa;
	DIR *d;
	struct dirent *dir;

	*interfaceList = NULL;

	fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP);
	if (fd < 0) goto skip;

fprintf(stderr, "Kpl-ANDROID Enumerate Interfaces:\n");
	d = opendir("/sys/class/net");
	if (0 == d) {
		BAIL(kFskErrNetworkInterfaceError);
	}

	while ((dir = readdir(d))) {
#if IGNORE_NETINTERFACE
		Boolean ignore = false;
		int i;
#endif
		char *ifname;
		unsigned int theIP = 0, theNetmask = 0, theStatus = 0;

		if (dir->d_name[0] == '.')
			continue;
		ifname = dir->d_name;
fprintf(stderr, "  -- %s: ", ifname);

#if IGNORE_NETINTERFACE
		i = NUM_IGNORE_NET;
		while (i) {
			if (FskStrCompare(ignoreInterfaces[i-1], ifname) == 0) {
				fprintf(stderr, " IGNORED");
				ignore = true;
			}
			i--;
		}
		if (ignore)
			continue;
#endif /* IGNORE_NETINTERFACE */	

		memset (&ifr, 0, sizeof(struct ifreq));
		strncpy(ifr.ifr_name, ifname, IFNAMSIZ);
		ifr.ifr_name[IFNAMSIZ - 1] = 0;

		if (ioctl(fd, SIOCGIFADDR, &ifr) >= 0) {
			sa = (struct sockaddr_in*)(void*)&(ifr.ifr_addr);
			theIP = ntohl(sa->sin_addr.s_addr);
		}

		if (ioctl(fd, SIOCGIFNETMASK, &ifr) >= 0) {
			sa = (struct sockaddr_in*)(void*)&(ifr.ifr_addr);
			theNetmask = ntohl(sa->sin_addr.s_addr);
		}

		if (ioctl(fd, SIOCGIFFLAGS, &ifr) >= 0) {
			if (ifr.ifr_flags & 1)
				theStatus = 1;
		}

		if (theIP == 0)
			theStatus = 0;

fprintf(stderr, "IP: %x, Netmask: %x [%s]", theIP, theNetmask, theStatus ? "UP" : "DOWN");

		if (ioctl(fd, SIOCGIFHWADDR, &ifr) >= 0) {
fprintf(stderr, " Got HWADDR ");
			if (ifr.ifr_hwaddr.sa_family == ARPHRD_ETHER) {
fprintf(stderr, "ETHER");
				FskMemPtrNewClear(sizeof(KplNetInterfaceRecord), (FskMemPtr*)(void*)&nir);
				if (!nir) {
					closedir(d);
					BAIL(kFskErrMemFull);
				}
				FskMemCopy(nir->MAC, ifr.ifr_hwaddr.sa_data, 6);

				nir->name = FskStrDoCopy(ifname);
				nir->ip = theIP;
				nir->netmask = theNetmask;
				nir->status = theStatus;

				FskListAppend((FskList*)interfaceList, nir);
			}
			else {
fprintf(stderr, " Family not ETHER -- huh?");
			}
		}
	}
	closedir(d);
skip:

	err = FskMemPtrNewClear(sizeof(KplNetInterfaceRecord), (FskMemPtr*)(void*)&nir);
	if (kFskErrNone == err) {
		nir->name = FskStrDoCopy("localhost");
		nir->ip = FskNetMakeIP(127, 0, 0, 1);
		nir->netmask = 0xff000000;
		nir->status = 1;
		FskListAppend((FskList*)interfaceList, nir);
	}

bail:
	if (fd >= 0)
		close(fd);

	return err;
}
Ejemplo n.º 24
0
void
xs_x509_decodeSubjectKeyId(xsMachine *the)
{
	UInt32 sz = xsToInteger(xsGet(xsArg(0), xsID("length")));
	unsigned char *p = xsGetHostData(xsArg(0)), *endp = p + sz, *endTBS, *endEXT, *extnID, *spki, *spk;
	int l, extnIDLen, spkLen;
	static UInt8 id_ce_ski[] = {2 * 40 + 5, 29, 14};	/* [2, 5, 29, 14] */

#define getTag()	(p < endp ? (int)*p++ : -1)
#define getBerLen()	_getBerLen(&p, endp)
#define nextTag()	(getTag(), l = getBerLen(), p += l)

	if (getTag() != 0x30)
		return;
	if ((l = getBerLen()) < 0)
		return;
	if (p + l > endp)
		return;
	/* TBSCertficate */
	if (getTag() != 0x30)
		return;
	if ((l = getBerLen()) < 0)
		return;
	if ((endTBS = p + l) > endp)
		return;
	if (*p & 0x80) {
		/* EXPLICT Version */
		p++;
		nextTag();
	}
	nextTag();	/* serialNumber */
	nextTag();	/* signature */
	nextTag();	/* issuer */
	nextTag();	/* validity */
	nextTag();	/* subject */
	spki = p;	/* subjectPublicKeyInfo */
	nextTag();
	/* OPTIONAL */
	while (p < endTBS) {
		int tag = getTag();
		if ((l = getBerLen()) < 0)
			return;
		switch (tag & 0x1f) {
		case 1:	/* issuerUniqueID */
		case 2:	/* subjectUniqueID */
			p += l;
			continue;	/* goto the next tag */
		case 3:	/* extensions */
			break;	/* fall thru */
		default:
			return;
		}
		/* must be a SEQUENCE of [1..MAX] */
		if (getTag() != 0x30)
			return;
		if ((l = getBerLen()) < 0)
			return;
		endEXT = p + l;
		while (p < endEXT) {
			/* must be a SEQUENCE of {extnID, critical, extnValue} */
			if (getTag() != 0x30)
				return;
			if ((l = getBerLen()) < 0)
				return;
			/* extnID: OBJECT ID */
			if (getTag() != 0x06)
				return;
			if ((extnIDLen = getBerLen()) < 0)
				return;
			extnID = p;
			p += extnIDLen;
			/* critical: BOOLEAN */
			if (*p == 0x01)
				nextTag();
			/* extnValue: OCTET STRING */
			if (getTag() != 0x04)
				return;
			if ((l = getBerLen()) < 0)
				return;
			if (extnIDLen == sizeof(id_ce_ski) && FskMemCompare(extnID, id_ce_ski, extnIDLen) == 0) {
				/* SKI: OCTET STRING */
				if (getTag() != 0x04)
					return;
				l = getBerLen();
				xsResult = xsNew1(xsGlobal, xsID("Chunk"), xsInteger(l));
				FskMemCopy(xsGetHostData(xsResult), p, l);
				return;
			}
			p += l;
		}
	}
	{
		/*
		 * Couldn't find Subject Key Identifier. Make up the ID from the Subject Public Key
		 */
		struct sha1 sha1;

		p = spki;
		if (getTag() != 0x30)
			return;	/* should be a SEQUENCE */
		l = getBerLen();
		/* skip AlgorithmIdentifier */
		nextTag();
		if (getTag() != 0x03)
			return;	/* should be a BIT STRING */
		spkLen = getBerLen();
		spk = p;
		xsResult = xsNew1(xsGlobal, xsID("Chunk"), xsInteger(SHA1_DGSTSIZE));
		sha1_create(&sha1);
		sha1_update(&sha1, spk, spkLen);
		sha1_fin(&sha1, xsGetHostData(xsResult));
	}
}
Ejemplo n.º 25
0
FskErr KprSoundLoad(KprSound self)
{
	FskErr err = kFskErrNone;
	char *path = NULL;
	FskFile fref = NULL;
	FskMediaSpoolerRecord spooler;
	KprSoundLoadSpoolerRefconRecord refcon;
	FskMediaReader reader = NULL;
	FskMediaReaderTrack track;
	FskMediaPropertyValueRecord property;
	char *audioFormat = NULL;
	double duration;
	unsigned char *formatInfo = NULL;
	UInt32 formatInfoSize;
	UInt16 numChannels;
	double sampleRate;
	double timeScale;
	FskMediaReaderSampleInfo info = NULL;
	unsigned char *buffer = NULL;
	KprSoundFrame frames = NULL;
	UInt32 frameCount = 0;
	unsigned char *data = NULL;
	UInt32 dataSize = 0;

	if (self->data) goto bail;

	bailIfError(KprURLToPath(self->url, &path));
	if (!self->mime) {
		unsigned char buffer[4096];
		UInt32 size;
        char *sniff = NULL;
		bailIfError(FskFileOpen(path, kFskFilePermissionReadOnly, &fref));
		bailIfError(FskFileRead(fref, sizeof(buffer), buffer, &size));
		FskFileClose(fref);
		fref = NULL;
		bailIfError(FskMediaPlayerSniffForMIME(buffer, size, NULL, self->url, &sniff));
		self->mime = sniff;
	}
	FskMemSet(&spooler, 0, sizeof(spooler));
	FskMemSet(&refcon, 0, sizeof(refcon));
	refcon.path = path;
	spooler.refcon = &refcon;
	spooler.doOpen = KprSoundLoadSpoolerOpen;
	spooler.doClose = KprSoundLoadSpoolerClose;
	spooler.doRead = KprSoundLoadSpoolerRead;
	spooler.doGetSize = KprSoundLoadSpoolerGetSize;
	bailIfError((*FskMediaReaderNewProc)(&reader, self->mime, self->url, &spooler, NULL, NULL));
	bailIfError((*FskMediaReaderGetPropertyProc)(reader, kFskMediaPropertyTimeScale, &property));
	timeScale = property.value.integer;
	(*FskMediaReaderGetPropertyProc)(reader, kFskMediaPropertyDuration, &property);
	duration = property.value.number;
	(*FskMediaReaderGetTrackProc)(reader, 0, &track);
	(*FskMediaReaderTrackGetPropertyProc)(track, kFskMediaPropertyFormat, &property);
	audioFormat = property.value.str;
	if (kFskErrNone == (*FskMediaReaderTrackGetPropertyProc)(track, kFskMediaPropertyFormatInfo, &property)) {
		formatInfo = property.value.data.data;
		formatInfoSize = property.value.data.dataSize;
	}
	else
		formatInfoSize = 0;

	(*FskMediaReaderTrackGetPropertyProc)(track, kFskMediaPropertyChannelCount, &property);
	numChannels = property.value.integer;
	(*FskMediaReaderTrackGetPropertyProc)(track, kFskMediaPropertySampleRate, &property);
	sampleRate = property.value.integer;
	bailIfError((*FskMediaReaderStartProc)(reader, NULL, NULL));
	for (;;) {
		UInt32 c = 0, i, s;
		unsigned char *d;
		err = (*FskMediaReaderExtractProc)(reader, &track, &c, &info, &buffer);
        if (err == kFskErrEndOfFile) {
            err = kFskErrNone;
            break;
        }
        if (err != kFskErrNone)
            goto bail;
		for (i = 0, d = buffer; i < c; i++, d += s) {
			s = info[i].sampleSize * info[i].samples;
            bailIfError(FskMemPtrRealloc((frameCount + 1) * sizeof(KprSoundFrameRecord), &frames));
			frames[frameCount].count = info[i].samples;
			frames[frameCount].frameSize = info[i].sampleSize;
			frames[frameCount].samplesPerFrame = info[i].sampleDuration;
			frames[frameCount].frameOffset = dataSize;
            frameCount++;
			bailIfError(FskMemPtrRealloc(dataSize + s, &data));
			FskMemCopy(data + dataSize, d, s);
			dataSize += s;
		}
		FskMemPtrDispose(buffer);
		buffer = NULL;
		FskMemPtrDispose(info);
		info = NULL;
	}
	(*FskMediaReaderStopProc)(reader);
	self->audioFormat = audioFormat;
	self->duration = duration;
	self->formatInfo = formatInfo;
	self->formatInfoSize = formatInfoSize;
	self->numChannels = numChannels;
	self->sampleRate = sampleRate;
	self->timeScale = timeScale;
	self->data = data;
	self->dataSize = dataSize;
	self->frames = frames;
	self->frameCount = frameCount;
bail:
	if (err) {
		FskMemPtrDispose(data);
		FskMemPtrDispose(frames);
		FskMemPtrDispose(formatInfo);
		FskMemPtrDispose(audioFormat);
	}
	FskMemPtrDispose(buffer);
	FskMemPtrDispose(info);
	(*FskMediaReaderDisposeProc)(reader);
    FskFileClose(fref);
	FskMemPtrDispose(path);
	return err;
}
Ejemplo n.º 26
0
// ------------------------------------------------------------------------
static int sParseStartLine(char *startLine, UInt16 headerType, FskHeaders *headers)
{
	FskErr	err;
	int		l;
	const char *p;
	char *c = startLine;
	char *firstPart;

	// Get method or protocol
	p = c;
	c = FskStrChr(c, ' ');
	if (!c) return -1;
	
	l = (c++) - p;
	err = FskMemPtrNew(l+1, &firstPart);
	if (err != kFskErrNone)
		return -1;
	FskStrNCopy(firstPart, p, l);
	firstPart[l] = '\0';
	if (kFskHeaderTypeResponse == headerType)
		headers->protocol = firstPart;
	else 
		headers->method = firstPart;

	c = FskStrStripHeadSpace(c);	// skip over space

	headers->headerType = headerType;
	if (kFskHeaderTypeResponse == headerType) {
		// Get response code and message (if message not in HTTP_Responses)
		headers->responseCode = FskStrToNum(c);
		if (headers->flags & kFskHeadersNonStandardResponseReasonPhrase) {
			c = FskStrChr(c, ' ');
			if (c) {
				char *r, *s;
				s = FskStrStripHeadSpace(c);
				r = FskFindResponse(headers->responseCode);
				if (!r || (0 != FskStrCompareCaseInsensitiveWithLength(s, r, FskStrLen(r)))) {
					headers->responseReasonPhrase = FskStrDoCopy(s);
					if (NULL != headers->responseReasonPhrase)
						FskStrStripTailSpace(headers->responseReasonPhrase);
				}
			}
		}
	}
	else {
		char 	*s, *t = NULL;
		char	*uri = NULL;

		// Get URI
		if ((*c == '/') && !(headers->flags & kFskHeadersDoNotStripURILeadingSlash))
			c++;
		s = FskStrChr(c, ' ');
		if (!s) {
			headers->responseCode = 400;
			return -1;
		}
		headers->protocol = FskStrDoCopy(s + 1);
		if (NULL != headers->protocol)
			FskStrStripTailSpace(headers->protocol);

		BAIL_IF_ERR(FskMemPtrNew((s-c)+1, &uri));
		BAIL_IF_ERR(FskMemPtrNew((s-c)+1, &t));
		FskMemCopy(uri, c, s-c);
		uri[s-c] = '\0';
		s = FskStrChr(uri, '?');
        if (s) *s = 0;
        FskStrDecodeEscapedChars(uri, t);
        if (s) {
            *s = '?';
            FskStrCat(t, s);
        }
		headers->URI = FskStrDoCopy(t);

		// Break URI into filename and parameters
		s = FskStrChr(t, '?');
		if (!s) {
			headers->filename = FskStrDoCopy(t);
		}
		else {		// URI has parameters
			*s++ = '\0';	// cap off the filename
			headers->filename = FskStrDoCopy(t);
			
			headers->parameters = FskAssociativeArrayNew();
			while (s) {
				char *name = s;		
				char *value = FskStrChr(name, '=');
				if (!value)
					break;
				s = FskStrChr(value, '&');
				*value++ = '\0';		// cap off the name
				if (s)
					*s++ = '\0';		// cap off the value
				FskAssociativeArrayElementSetString(headers->parameters, name, value);
			}
		}		

bail:
		FskMemPtrDispose(uri);
		FskMemPtrDispose(t);

	}

	return headers->headerType;
}
Ejemplo n.º 27
0
void KPR_shell_splitError(xsMachine* the)
{
	xsStringValue string, p, q;
	char c;
	xsIndex ids[4];
	size_t offsets[4], lengths[4];
	int i;
	xsVars(1);
	string = p = xsToString(xsArg(0));
	ids[0] = xsID_path;
	offsets[0] = p - string;
	c = *p;
	if (c == '/')
		p = FskStrChr(p, ':');
	else if (('A' <= c) && (c <= 'Z') && (*(p + 1) == ':'))
		p = FskStrChr(p + 2, ':');
	else
		goto bail;
	if (!p) goto bail;
	ids[1] = xsID_line;
	q = p - 1;
	c = *q;
	if (c == ')') {
		q--;
		while ((q > string) && ((c = *q)) && ('0' <= c) && (c <= '9'))
			q--;
		if (c != '(') goto bail;
		lengths[0] = q - string;
		offsets[1] = q + 1 - string;
		lengths[1] = (p - q) - 2;
	}
	else {
		lengths[0] = p - string;
		p++;
		offsets[1] = p - string;
		while (((c = *p)) && ('0' <= c) && (c <= '9'))
			p++;
		if (c != ':') goto bail;
		lengths[1] = (p - string) - offsets[1];
	}
	p++;
	c  = *p;
	if (('0' <= c) && (c <= '9')) {
		p++;
		while (((c = *p)) && ('0' <= c) && (c <= '9'))
			p++;
		if (c != ':') goto bail;
		p++;
		c  = *p;
	}
	if (c != ' ') goto bail;
	p++;
	ids[2] = xsID_kind;
	offsets[2] = p - string;
	p = FskStrChr(p, ':');
	if (!p) goto bail;
	lengths[2] = (p - string) - offsets[2];
	p++;
	c = *p;
	if (c != ' ') goto bail;
	p++;
	ids[3] = xsID_reason;
	offsets[3] = p - string;
	lengths[3] = FskStrLen(p);
	xsResult = xsNewInstanceOf(xsObjectPrototype);
	for (i = 0; i < 4; i++) {
		xsVar(0) = xsStringBuffer(NULL, lengths[i]);
		string = xsToString(xsArg(0));
		FskMemCopy(xsToString(xsVar(0)), string + offsets[i], lengths[i]);
		xsNewHostProperty(xsResult, ids[i], xsVar(0), xsDefault, xsDontScript);
	}
bail:
	return;
}
Ejemplo n.º 28
0
static FskErr sFskNetInterfaceEnumerate(FskNetInterfaceRecord **interfaceList)
{
	FskErr	err = kFskErrNone;
	FskNetInterfaceRecord *nir;
	int fd;
	struct ifreq  ifr;
	struct sockaddr_in *sa;
#if TARGET_OS_MAC	// BSD
	struct ifreq ibuf[32];
#endif /* TARGET_OS_MAC */
#if TARGET_OS_LINUX
#if TARGET_OS_ANDROID
	DIR *d;
	struct dirent *dir;
	*interfaceList = NULL;

	fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP);
	if (fd < 0) goto skip;

	FskInstrumentedTypePrintfDebug(&gNetInterfaceNotifierTypeInstrumentation, "Enumerate Interfaces:");

	d = opendir("/sys/class/net");
	if (0 == d)  {
		BAIL(kFskErrNetworkInterfaceError);
	}

	while ((dir = readdir(d))) {
#if IGNORE_NETINTERFACE
		Boolean ignore = false;
		int i;
#endif
		char *ifname;
		unsigned theIP = 0, theNetmask = 0, theStatus = 0;

		if (dir->d_name[0] == '.')
			continue;

		ifname = dir->d_name;

		FskInstrumentedTypePrintfDebug(&gNetInterfaceNotifierTypeInstrumentation,"%s: ", ifname);

#if IGNORE_NETINTERFACE
		i = NUM_IGNORE_NET;
		while (i) {
			if (FskStrCompare(ignoreInterfaces[i-1], ifname) == 0) {
				FskInstrumentedTypePrintfDebug(&gNetInterfaceNotifierTypeInstrumentation, "IGNORED");
				ignore = true;
			}
			i--;
		}
		if (ignore)
			continue;
#endif /* IGNORE_NETINTERFACE */

		memset(&ifr, 0,  sizeof(struct ifreq));
		strncpy(ifr.ifr_name, ifname, IFNAMSIZ);
		ifr.ifr_name[IFNAMSIZ - 1] = 0;

		if (ioctl(fd, SIOCGIFADDR, &ifr) >= 0) {
			sa = (struct sockaddr_in*)(void*)&(ifr.ifr_addr);
			theIP = ntohl( sa->sin_addr.s_addr);
		}

		if (ioctl(fd, SIOCGIFNETMASK, &ifr) >= 0) {
			sa = (struct sockaddr_in*)(void*)&(ifr.ifr_addr);
			theNetmask = ntohl( sa->sin_addr.s_addr);
		}

		if (ioctl(fd, SIOCGIFFLAGS, &ifr) >= 0) {
			if (ifr.ifr_flags & 1)
				theStatus = 1;
		}

		if (theIP == 0)
			theStatus = 0;

		FskInstrumentedTypePrintfDebug(&gNetInterfaceNotifierTypeInstrumentation,"IP: %x, Netmask: %x [%s]", theIP, theNetmask, theStatus ? "UP " : "DOWN ");

		if (ioctl(fd, SIOCGIFHWADDR, &ifr) >= 0) {
			FskInstrumentedTypePrintfDebug(&gNetInterfaceNotifierTypeInstrumentation, "Got HWADDR ");

			if (ifr.ifr_hwaddr.sa_family == ARPHRD_ETHER) {
				FskInstrumentedTypePrintfDebug(&gNetInterfaceNotifierTypeInstrumentation, " ETHER");
				FskMemPtrNewClear(sizeof(FskNetInterfaceRecord), (FskMemPtr*)(void*)&nir);
				if (!nir) {
					closedir(d);
					BAIL(kFskErrMemFull);
				}
				FskMemCopy(nir->MAC, ifr.ifr_hwaddr.sa_data, 6);

				nir->name = FskStrDoCopy(ifname);
				nir->ip = theIP;
				nir->netmask = theNetmask;
				nir->status = theStatus;

				FskListAppend((FskList*)interfaceList, nir);
			}
			else {
				FskInstrumentedTypePrintfDebug(&gNetInterfaceNotifierTypeInstrumentation, " Family not ETHER Huh?");
			}
		}
	}
	closedir(d);
skip:

#else /* !TARGET_OS_ANDROID */
	FILE *fp;
	char buf[256];
#if IGNORE_NETINTERFACE
	Boolean ignore = false;
	int i;
#endif

	*interfaceList = NULL;
	fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP);
	if (fd < 0) goto skip;

	fp = fopen("/proc/net/dev", "r");
	if (!fp) {
		BAIL(kFskErrNetworkInterfaceError);
	}
	// ignore two lines
	fgets(buf, sizeof(buf), fp);
	fgets(buf, sizeof(buf), fp);
	while (fgets(buf, sizeof(buf), fp)) {
		char *ifname = strtok(buf, " :");
		if (!ifname) continue;

		FskInstrumentedTypePrintfDebug(&gNetInterfaceNotifierTypeInstrumentation,"%s: ", ifname);

#if IGNORE_NETINTERFACE
		i = NUM_IGNORE_NET;
		while (i) {
			if (FskStrCompare(ignoreInterfaces[i-1], ifname) == 0) {
				FskInstrumentedTypePrintfDebug(&gNetInterfaceNotifierTypeInstrumentation, "IGNORED");
				ignore = true;
			}
			i--;
		}
		if (ignore)
			continue;
#endif /* IGNORE_NETINTERFACE */
		strcpy(ifr.ifr_name, ifname);
		if ((ioctl(fd, SIOCGIFHWADDR, &ifr) != -1) && (ifr.ifr_hwaddr.sa_family == ARPHRD_ETHER)) {
			FskMemPtrNewClear(sizeof(FskNetInterfaceRecord), (FskMemPtr *)&nir);
			if (!nir) {
				err = kFskErrMemFull;
				fclose(fp);
				goto bail;
			}
			FskMemCopy(nir->MAC, ifr.ifr_hwaddr.sa_data, 6);
			nir->name = FskStrDoCopy(ifname);

			nir->ip = 0;
			if (ioctl(fd, SIOCGIFADDR, &ifr) != -1) {
				sa = (struct sockaddr_in*)(void*)&(ifr.ifr_addr);
				nir->ip = ntohl( sa->sin_addr.s_addr);
			}

			if (ioctl(fd, SIOCGIFNETMASK, &ifr) != -1) {
				sa = (struct sockaddr_in*)(void*)&(ifr.ifr_addr);
				nir->netmask = ntohl( sa->sin_addr.s_addr);
			}

			if (ioctl(fd, SIOCGIFFLAGS, &ifr) != -1) {
				if (ifr.ifr_flags & IFF_UP) {
					nir->status = 1;
				} else {
					nir->status = 0;
				}
			}

			if (nir->ip == 0)
				nir->status = 0;

			FskInstrumentedTypePrintfDebug(&gNetInterfaceNotifierTypeInstrumentation,"IP: %x, Netmask: %x [%s] HWADDR [%02x:%02x:%02x:%02x:%02x:%02x]", theIP, theNetmask, theStatus ? "UP " : "DOWN ", nir->MAC[0], nir->MAC[1], nir->MAC[2], nir->MAC[3], nir->MAC[4], nir->MAC[5]);
			FskListAppend((FskList*)interfaceList, nir);
		}
		else {
			FskInstrumentedTypePrintfDebug(&gNetInterfaceNotifierTypeInstrumentation, " Family not ETHER or no HWADDR");
		}
	}
	fclose(fp);
skip:
#endif /* !TARGET_OS_ANDROID */

#elif TARGET_OS_MAC && !TARGET_OS_IPHONE
	struct ifreq *ifrp, *ifend;
	unsigned int r;
	struct ifconf ifc;
#if IGNORE_NETINTERFACE
	Boolean ignore = false;
	int i;
#endif

	*interfaceList = NULL;
	fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP);
	ifc.ifc_len = sizeof(ibuf);
	ifc.ifc_buf = (caddr_t)ibuf;
	if (ioctl(fd, SIOCGIFCONF, &ifc) == -1 ||
		ifc.ifc_len < (int)sizeof(struct ifreq)) {
		BAIL(kFskErrNetworkInterfaceError);
	}

	ifrp = ibuf;
	ifend = (struct ifreq*)((char*)ibuf + ifc.ifc_len);
	while (ifrp < ifend) {
		if (ifrp->ifr_addr.sa_family == AF_LINK &&
			((struct sockaddr_dl *)&ifrp->ifr_addr)->sdl_type == IFT_ETHER) {
			err = FskMemPtrNewClear(sizeof(FskNetInterfaceRecord), (FskMemPtr *)&nir);
			BAIL_IF_ERR(err);
			nir->name = FskStrDoCopy(ifrp->ifr_name);
			FskMemCopy((char*)nir->MAC, (char*)LLADDR((struct sockaddr_dl *)&ifrp->ifr_addr), 6);

			FskInstrumentedTypePrintfDebug(&gNetInterfaceNotifierTypeInstrumentation,"%s: ", nir->name);

#if IGNORE_NETINTERFACE
			i = NUM_IGNORE_NET;
			ignore = false;
			while (i) {
				if (FskStrCompare(ignoreInterfaces[i-1], nir->name) == 0) {
					FskInstrumentedTypePrintfDebug(&gNetInterfaceNotifierTypeInstrumentation, "IGNORED");
					ignore = true;
				}
				i--;
			}
			if (ignore) {
				FskMemPtrDispose(nir->name);
				FskMemPtrDisposeAt(&nir);
				goto nextOne;
			}
#endif /* IGNORE_NETINTERFACE */

			strcpy(ifr.ifr_name, nir->name);		//@@ bounds check needed?
			if (ioctl(fd, SIOCGIFADDR, &ifr) != -1) {
				sa = (struct sockaddr_in*)(void*)&(ifr.ifr_addr);
				nir->ip = ntohl( sa->sin_addr.s_addr);
			}
			if (nir->ip) {
				if (ioctl(fd, SIOCGIFNETMASK, &ifr) != -1) {
					sa = (struct sockaddr_in*)(void*)&(ifr.ifr_addr);
					nir->netmask = ntohl( sa->sin_addr.s_addr);
				}

				if (ioctl(fd, SIOCGIFFLAGS, &ifr) != -1) {
					if (ifr.ifr_flags & IFF_UP)
						nir->status = 1;
				}

				FskInstrumentedTypePrintfDebug(&gNetInterfaceNotifierTypeInstrumentation,"IP: %x, Netmask: %x [%s] HWADDR [%02x:%02x:%02x:%02x:%02x:%02x]", nir->ip, nir->netmask, nir->status ? "UP " : "DOWN ", nir->MAC[0], nir->MAC[1], nir->MAC[2], nir->MAC[3], nir->MAC[4], nir->MAC[5]);

				FskListAppend(interfaceList, nir);
			}
			else {
				FskMemPtrDispose(nir->name);
				FskMemPtrDisposeAt(&nir);
			}
		}

nextOne:
		r = ifrp->ifr_addr.sa_len + sizeof(ifrp->ifr_name);
		if (r < sizeof(*ifrp))
			r = sizeof(*ifrp);
		ifrp = (struct ifreq*)((char*)ifrp+r);
	}

#elif TARGET_OS_IPHONE
	struct ifaddrs *iflist;
	if (getifaddrs(&iflist) != 0)
		return kFskErrNetworkInterfaceError;
	*interfaceList = NULL;
	for (struct ifaddrs *ifa = iflist; ifa != NULL; ifa = ifa->ifa_next) {
		if (ifa->ifa_name == NULL || ifa->ifa_addr == NULL || ifa->ifa_netmask == NULL || ((struct sockaddr_in*)(void*)ifa->ifa_addr)->sin_addr.s_addr == 0)
			continue;
		for (FskNetInterface ni = *interfaceList; ni != NULL; ni = ni->next) {
			if (FskStrCompare(ni->name, ifa->ifa_name) == 0)
				goto next;
		}
		if ((err = FskMemPtrNewClear(sizeof(FskNetInterfaceRecord), (FskMemPtr *)&nir)) != kFskErrNone)
			return err;
		nir->name = FskStrDoCopy(ifa->ifa_name);
		nir->ip = ntohl(((struct sockaddr_in*)(void*)ifa->ifa_addr)->sin_addr.s_addr);
		nir->netmask = ntohl(((struct sockaddr_in*)(void*)ifa->ifa_netmask)->sin_addr.s_addr);
		nir->status = ifa->ifa_flags & IFF_UP ? 1 : 0;
		FskListAppend((FskList *)interfaceList, nir);
	next:;
	}
	freeifaddrs(iflist);
	return kFskErrNone;
#endif /* TARGET_OS_IPHONE */

	// add loop back I/F to total number of IP addresses
	err = FskMemPtrNewClear(sizeof(FskNetInterfaceRecord), (FskMemPtr*)(void*)&nir);
	if (kFskErrNone == err) {
		nir->name = FskStrDoCopy("localhost");
		nir->ip = FskNetMakeIP(127,0,0,1);
		nir->netmask = 0xff000000;
		nir->status = 1;
		FskListAppend((FskList*)interfaceList, nir);
	}

bail:
	if (fd >= 0)		// coverity 10587
		close (fd);
	return err;
}
Ejemplo n.º 29
0
UInt32 KprMemoryBufferCopyTo(KprMemoryBuffer self, void *dest)
{
	FskMemCopy(dest, self->buffer, self->size);
	return self->size;
}
Ejemplo n.º 30
0
//
// /etc/vold.fstab
// Format: dev_mount <label> <mount_point> <part> <sysfs_path1...>
//
void scanVoldFstab() {
	FskErr err;
	FILE *mntFile;
	char *mntFileBuffer;
	int bufEnd = 0;
	int done = 0;
	int amt;
	char *bufPos, *lineEnd;

	mntFile = FOPEN(VOLD_FSTAB_FILE, "r");
	if (NULL == mntFile) {
		FskAndroidFilesPrintfDebug("failed opening %s - %d\n", VOLD_FSTAB_FILE, errno);
//		oldscanVolumes();
		return;
	}

	err = FskMemPtrNew(MOUNT_BUF_SIZE + 1, &mntFileBuffer);
	BAIL_IF_ERR(err);
	bufPos = mntFileBuffer;

	while (!done) {
		// fill the buffer
		amt = fread(mntFileBuffer + bufEnd, 1, MOUNT_BUF_SIZE - bufEnd, mntFile);
		FskAndroidFilesPrintfDebug("fread %x, %d - got %d\n", mntFileBuffer + bufEnd, MOUNT_BUF_SIZE - bufEnd, amt);
		if (amt > 0) {
			bufEnd += amt;
		}
		mntFileBuffer[bufEnd] = '\0';

		FskAndroidFilesPrintfDebug("check while(bufpos...) - %d < %d\n", bufPos, mntFileBuffer + bufEnd);
		while (bufPos < mntFileBuffer + bufEnd) {
			extMount	mnt = NULL;
			char fsName[256], fsMnt[256], tmp[256], fsPath[256];

			// Format: dev_mount <label> <mount_point> <part> <sysfs_path1...>
			if (NULL == (lineEnd = FskStrChr(bufPos, kFskLF)))
				break;

			bufPos = FskStrNCopyUntilSpace(tmp, bufPos, 255);
			if (0 != FskStrCompare(tmp, "dev_mount")) {
				// no dev_mount, move bufPos to end of line and then continue;
				FskAndroidFilesPrintfDebug("didn't find dev_mount in '%s' - bail\n", tmp);
				bufPos = lineEnd + 1;
				continue;
			}

			// Format: dev_mount <label> <mount_point> <part> <sysfs_path1...>
			bufPos = FskStrNCopyUntilSpace(fsName, bufPos, 255);
			bufPos = FskStrNCopyUntilSpace(fsMnt, bufPos, 255);
			bufPos = FskStrNCopyUntilSpace(tmp, bufPos, 255);
			bufPos = FskStrNCopyUntilSpace(fsPath, bufPos, 255);
			FskAndroidFilesPrintfDebug("got Name: %s Mnt: %s tmp: %s fsPath: %s\n", fsName, fsMnt, tmp, fsPath);

			err = FskMemPtrNew(sizeof(extMountRec), &mnt);
			BAIL_IF_ERR(err);
			mnt->label = FskStrDoCopy(fsName);
			mnt->mountPoint = FskStrDoCopy(fsMnt);
			FskAndroidFilesPrintfDebug("Make an external filesystem record with label: %s, mountPoint: %s\n", mnt->label, mnt->mountPoint);
			FskListAppend(&gExtMounts, mnt);

			bufPos = lineEnd + 1;
		}

		if (amt == 0) {	// we read no more
			done = 1;
		}
		else {
			// push buffer to beginning
			amt = (mntFileBuffer + bufEnd) - bufPos;
			FskAndroidFilesPrintfDebug("push unread %d bytes to beginning of buffer\n - mntFileBuffer: %d  bufEnd: %d  bufPos: %d", amt, mntFileBuffer, bufEnd, bufPos);
			if (amt > 0) {
				FskMemCopy(mntFileBuffer, bufPos, amt);
				bufEnd = amt;
			}
			else
				bufEnd = 0;
			bufPos = mntFileBuffer;
		}
	}

bail:

	fclose(mntFile);
}