Merge branch 'library' into master

This commit is contained in:
Iwan Timmer
2015-07-23 17:35:55 +02:00
25 changed files with 968 additions and 643 deletions

View File

@@ -1,397 +0,0 @@
/*
* This file is part of Moonlight Embedded.
*
* Copyright (C) 2015 Iwan Timmer
*
* Moonlight 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.
*
* Moonlight 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 Moonlight; if not, see <http://www.gnu.org/licenses/>.
*/
#include "http.h"
#include "xml.h"
#include "mkcert.h"
#include "client.h"
#include "limelight-common/Limelight.h"
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
#include <openssl/sha.h>
#include <openssl/aes.h>
#include <openssl/rand.h>
#include <openssl/evp.h>
#include <openssl/x509.h>
#include <openssl/pem.h>
#include <openssl/err.h>
static const char *uniqueFileName = "uniqueid.dat";
static const char *certificateFileName = "client.pem";
static const char *p12FileName = "client.p12";
static const char *keyFileName = "key.pem";
#define UNIQUEID_BYTES 8
#define UNIQUEID_CHARS (UNIQUEID_BYTES*2)
static char unique_id[UNIQUEID_CHARS+1];
static X509 *cert;
static char cert_hex[4096];
static EVP_PKEY *privateKey;
static bool paired;
static int currentGame;
static int serverMajorVersion;
static void client_load_unique_id() {
FILE *fd = fopen(uniqueFileName, "r");
if (fd == NULL) {
unsigned char unique_data[UNIQUEID_BYTES];
RAND_bytes(unique_data, UNIQUEID_BYTES);
for (int i = 0; i < UNIQUEID_BYTES; i++) {
sprintf(unique_id + (i * 2), "%02x", unique_data[i]);
}
fd = fopen(uniqueFileName, "w");
fwrite(unique_id, UNIQUEID_CHARS, 1, fd);
} else {
fread(unique_id, UNIQUEID_CHARS, 1, fd);
}
fclose(fd);
unique_id[UNIQUEID_CHARS] = 0;
}
static void client_load_cert() {
FILE *fd = fopen(certificateFileName, "r");
if (fd == NULL) {
printf("Generating certificate...");
struct CertKeyPair cert = generateCertKeyPair();
printf("done\n");
saveCertKeyPair(certificateFileName, p12FileName, keyFileName, cert);
freeCertKeyPair(cert);
fd = fopen(certificateFileName, "r");
}
if (fd == NULL) {
fprintf(stderr, "Can't open certificate file\n");
exit(-1);
}
if (!(cert = PEM_read_X509(fd, NULL, NULL, NULL))) {
fprintf(stderr, "Error loading cert into memory.\n");
exit(-1);
}
rewind(fd);
int c;
int length = 0;
while ((c = fgetc(fd)) != EOF) {
sprintf(cert_hex + length, "%02x", c);
length += 2;
}
cert_hex[length] = 0;
fclose(fd);
fd = fopen(keyFileName, "r");
PEM_read_PrivateKey(fd, &privateKey, NULL, NULL);
fclose(fd);
}
static void client_load_server_status(const char *address) {
char url[4096];
sprintf(url, "https://%s:47984/serverinfo?uniqueid=%s", address, unique_id);
struct http_data *data = http_create_data();
http_request(url, data);
char *pairedText = NULL;
char *currentGameText = NULL;
char *versionText = NULL;
xml_search(data->memory, data->size, "currentgame", &currentGameText);
xml_search(data->memory, data->size, "PairStatus", &pairedText);
xml_search(data->memory, data->size, "appversion", &versionText);
http_free_data(data);
paired = pairedText != NULL && strcmp(pairedText, "1") == 0;
currentGame = currentGameText == NULL ? 0 : atoi(currentGameText);
char *versionSep = strstr(versionText, ".");
if (versionSep != NULL) {
*versionSep = 0;
}
serverMajorVersion = atoi(versionText);
free(pairedText);
free(currentGameText);
free(versionText);
}
static void bytes_to_hex(unsigned char *in, char *out, size_t len) {
for (int i = 0; i < len; i++) {
sprintf(out + i * 2, "%02x", in[i]);
}
out[len * 2] = 0;
}
static int sign_it(const char *msg, size_t mlen, unsigned char **sig, size_t *slen, EVP_PKEY *pkey) {
int result = -1;
*sig = NULL;
*slen = 0;
EVP_MD_CTX *ctx = EVP_MD_CTX_create();
if (ctx == NULL) {
fprintf(stderr, "EVP_MD_CTX_create failed, error 0x%lx\n", ERR_get_error());
return -1;
}
const EVP_MD *md = EVP_get_digestbyname("SHA256");
if (md == NULL) {
fprintf(stderr, "EVP_get_digestbyname failed, error 0x%lx\n", ERR_get_error());
goto cleanup;
}
int rc = EVP_DigestInit_ex(ctx, md, NULL);
if (rc != 1) {
fprintf(stderr, "EVP_DigestInit_ex failed, error 0x%lx\n", ERR_get_error());
goto cleanup;
}
rc = EVP_DigestSignInit(ctx, NULL, md, NULL, pkey);
if (rc != 1) {
fprintf(stderr, "EVP_DigestSignInit failed, error 0x%lx\n", ERR_get_error());
goto cleanup;
}
rc = EVP_DigestSignUpdate(ctx, msg, mlen);
if (rc != 1) {
fprintf(stderr, "EVP_DigestSignUpdate failed, error 0x%lx\n", ERR_get_error());
goto cleanup;
}
size_t req = 0;
rc = EVP_DigestSignFinal(ctx, NULL, &req);
if (rc != 1) {
fprintf(stderr, "EVP_DigestSignFinal failed (1), error 0x%lx\n", ERR_get_error());
goto cleanup;
}
if (!(req > 0)) {
fprintf(stderr, "EVP_DigestSignFinal failed (2), error 0x%lx\n", ERR_get_error());
goto cleanup;
}
*sig = OPENSSL_malloc(req);
if (*sig == NULL) {
fprintf(stderr, "OPENSSL_malloc failed, error 0x%lx\n", ERR_get_error());
goto cleanup;
}
*slen = req;
rc = EVP_DigestSignFinal(ctx, *sig, slen);
if (rc != 1) {
fprintf(stderr, "EVP_DigestSignFinal failed (3), return code %d, error 0x%lx\n", rc,
ERR_get_error());
goto cleanup;
}
if (req != *slen) {
fprintf(stderr, "EVP_DigestSignFinal failed, mismatched signature sizes %ld, %ld\n",
req, *slen);
goto cleanup;
}
result = 1;
cleanup:
EVP_MD_CTX_destroy(ctx);
ctx = NULL;
return !!result;
}
void client_pair(const char *address) {
char url[4096];
if (client_is_paired(NULL)) {
printf("Already paired\n");
return;
}
if (currentGame != 0) {
fprintf(stderr, "The computer is currently in a game. You must close the game before pairing.\n");
exit(-1);
}
char pin[5];
sprintf(pin, "%d%d%d%d", (int)random() % 10, (int)random() % 10, (int)random() % 10, (int)random() % 10);
printf("Please enter the following PIN on the target PC: %s\n", pin);
unsigned char salt_data[16];
char salt_hex[33];
RAND_bytes(salt_data, 16);
bytes_to_hex(salt_data, salt_hex, 16);
sprintf(url, "https://%s:47984/pair?uniqueid=%s&devicename=roth&updateState=1&phrase=getservercert&salt=%s&clientcert=%s", address, unique_id, salt_hex, cert_hex);
struct http_data *data = http_create_data();
http_request(url, data);
unsigned char salt_pin[20];
unsigned char aes_key_hash[20];
AES_KEY aes_key;
memcpy(salt_pin, salt_data, 16);
memcpy(salt_pin+16, salt_pin, 4);
SHA1(salt_pin, 20, aes_key_hash);
AES_set_encrypt_key((unsigned char *)aes_key_hash, 128, &aes_key);
unsigned char challenge_data[16];
unsigned char challenge_enc[16];
char challenge_hex[33];
RAND_bytes(challenge_data, 16);
AES_encrypt(challenge_data, challenge_enc, &aes_key);
bytes_to_hex(challenge_enc, challenge_hex, 16);
sprintf(url, "https://%s:47984/pair?uniqueid=%s&devicename=roth&updateState=1&clientchallenge=%s", address, unique_id, challenge_hex);
http_request(url, data);
char *result;
xml_search(data->memory, data->size, "challengeresponse", &result);
char challenge_response_data_enc[48];
char challenge_response_data[48];
for (int count = 0; count < strlen(result); count++) {
sscanf(&result[count], "%2hhx", &challenge_response_data_enc[count / 2]);
}
free(result);
for (int i = 0; i < 48; i += 16) {
AES_decrypt(&challenge_response_data_enc[i], &challenge_response_data[i], &aes_key);
}
char client_secret_data[16];
RAND_bytes(client_secret_data, 16);
char challenge_response[16 + 256 + 16];
char challenge_response_hash[32];
char challenge_response_hash_enc[32];
char challenge_response_hex[33];
memcpy(challenge_response, challenge_response_data + 20, 16);
memcpy(challenge_response + 16, cert->signature->data, 256);
memcpy(challenge_response + 16 + 256, client_secret_data, 16);
SHA1(challenge_response, 16 + 256 + 16, challenge_response_hash);
for (int i = 0; i < 32; i += 16) {
AES_encrypt(&challenge_response_hash[i], &challenge_response_hash_enc[i], &aes_key);
}
bytes_to_hex(challenge_response_hash_enc, challenge_response_hex, 32);
sprintf(url, "https://%s:47984/pair?uniqueid=%s&devicename=roth&updateState=1&serverchallengeresp=%s", address, unique_id, challenge_response_hex);
http_request(url, data);
xml_search(data->memory, data->size, "pairingsecret", &result);
unsigned char *signature = NULL;
size_t s_len;
if (!sign_it(client_secret_data, 16, &signature, &s_len, privateKey)) {
fprintf(stderr, "Failed to sign data\n");
exit(-1);
}
char client_pairing_secret[16 + 256];
char client_pairing_secret_hex[(16 + 256) * 2 + 1];
memcpy(client_pairing_secret, client_secret_data, 16);
memcpy(client_pairing_secret + 16, signature, 256);
bytes_to_hex(client_pairing_secret, client_pairing_secret_hex, 16 + 256);
sprintf(url, "https://%s:47984/pair?uniqueid=%s&devicename=roth&updateState=1&clientpairingsecret=%s", address, unique_id, client_pairing_secret_hex);
http_request(url, data);
sprintf(url, "https://%s:47984/pair?uniqueid=%s&devicename=roth&updateState=1&phrase=pairchallenge", address, unique_id);
http_request(url, data);
http_free_data(data);
printf("Paired\n");
}
struct app_list *client_applist(const char *address) {
char url[4096];
struct http_data *data = http_create_data();
sprintf(url, "https://%s:47984/applist?uniqueid=%s", address, unique_id);
http_request(url, data);
struct app_list *list = xml_applist(data->memory, data->size);
http_free_data(data);
return list;
}
int client_get_app_id(const char *address, const char *name) {
struct app_list *list = client_applist(address);
while (list != NULL) {
if (strcmp(list->name, name) == 0)
return list->id;
list = list->next;
}
return -1;
}
void client_start_app(STREAM_CONFIGURATION *config, const char *address, int appId, bool sops, bool localaudio) {
RAND_bytes(config->remoteInputAesKey, 16);
memset(config->remoteInputAesIv, 0, 16);
srand(time(NULL));
char url[4096];
u_int32_t rikeyid = 1;
char rikey_hex[33];
bytes_to_hex(config->remoteInputAesKey, rikey_hex, 16);
struct http_data *data = http_create_data();
if (currentGame == 0)
sprintf(url, "https://%s:47984/launch?uniqueid=%s&appid=%d&mode=%dx%dx%d&additionalStates=1&sops=%d&rikey=%s&rikeyid=%d&localAudioPlayMode=%d", address, unique_id, appId, config->width, config->height, config->fps, sops, rikey_hex, rikeyid, localaudio);
else
sprintf(url, "https://%s:47984/resume?uniqueid=%s&rikey=%s&rikeyid=%d", address, unique_id, rikey_hex, rikeyid);
http_request(url, data);
http_free_data(data);
}
void client_quit_app(const char *address) {
char url[4096];
struct http_data *data = http_create_data();
sprintf(url, "https://%s:47984/cancel?uniqueid=%s", address, unique_id);
http_request(url, data);
http_free_data(data);
}
bool client_is_paired(const char *address) {
if (address != NULL)
client_load_server_status(address);
return paired;
}
int client_get_current_game(const char *address) {
if (address != NULL)
client_load_server_status(address);
return currentGame;
}
void client_init(const char *address) {
http_init();
client_load_unique_id();
client_load_cert();
client_load_server_status(address);
}
int client_get_server_version(void) {
return serverMajorVersion;
}

View File

@@ -1,34 +0,0 @@
/*
* This file is part of Moonlight Embedded.
*
* Copyright (C) 2015 Iwan Timmer
*
* Moonlight 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.
*
* Moonlight 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 Moonlight; if not, see <http://www.gnu.org/licenses/>.
*/
#include "xml.h"
#include "limelight-common/Limelight.h"
#include "stdbool.h"
void client_init(const char* serverAddress);
void client_start_app(STREAM_CONFIGURATION *config, const char* serverAddress, int appId, bool sops, bool localaudio);
struct app_list* client_applist(const char* serverAddress);
int client_get_app_id(const char* serverAddress, const char* name);
void client_pair(const char *address);
int client_get_server_version(void);
bool client_is_paired(const char *address);
int client_get_current_game(const char *address);
void client_quit_app(const char *address);

View File

@@ -1,106 +0,0 @@
/*
* This file is part of Moonlight Embedded.
*
* Based on Avahi example client-browse-services
*
* Moonlight 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.
*
* Moonlight 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 Moonlight; if not, see <http://www.gnu.org/licenses/>.
*/
#include <avahi-client/client.h>
#include <avahi-client/lookup.h>
#include <avahi-common/simple-watch.h>
#include <avahi-common/malloc.h>
#include <avahi-common/error.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <time.h>
static AvahiSimplePoll *simple_poll = NULL;
static void discover_client_callback(AvahiClient *c, AvahiClientState state, void *userdata) {
if (state == AVAHI_CLIENT_FAILURE) {
fprintf(stderr, "Server connection failure: %s\n", avahi_strerror(avahi_client_errno(c)));
avahi_simple_poll_quit(simple_poll);
}
}
static void discover_resolve_callback(AvahiServiceResolver *r, AvahiIfIndex interface, AvahiProtocol protocol, AvahiResolverEvent event, const char *name, const char *type, const char *domain, const char *host_name, const AvahiAddress *address, uint16_t port, AvahiStringList *txt, AvahiLookupResultFlags flags, void *userdata) {
if (event == AVAHI_RESOLVER_FOUND) {
if (userdata != NULL) {
avahi_address_snprint(userdata, AVAHI_ADDRESS_STR_MAX, address);
avahi_simple_poll_quit(simple_poll);
} else {
char strAddress[AVAHI_ADDRESS_STR_MAX];
avahi_address_snprint(strAddress, sizeof(strAddress), address);
printf(" %s (%s)\n", host_name, strAddress);
}
}
avahi_service_resolver_free(r);
}
static void discover_browse_callback(AvahiServiceBrowser *b, AvahiIfIndex interface, AvahiProtocol protocol, AvahiBrowserEvent event, const char *name, const char *type, const char *domain, AvahiLookupResultFlags flags, void* userdata) {
AvahiClient *c = avahi_service_browser_get_client(b);
switch (event) {
case AVAHI_BROWSER_FAILURE:
fprintf(stderr, "(Discover) %s\n", avahi_strerror(avahi_client_errno(avahi_service_browser_get_client(b))));
avahi_simple_poll_quit(simple_poll);
break;
case AVAHI_BROWSER_NEW:
if (!(avahi_service_resolver_new(c, interface, protocol, name, type, domain, AVAHI_PROTO_UNSPEC, 0, discover_resolve_callback, userdata)))
fprintf(stderr, "Failed to resolve service '%s': %s\n", name, avahi_strerror(avahi_client_errno(c)));
break;
case AVAHI_BROWSER_REMOVE:
break;
}
}
void discover_server(char* dest) {
AvahiClient *client = NULL;
AvahiServiceBrowser *sb = NULL;
if (!(simple_poll = avahi_simple_poll_new())) {
fprintf(stderr, "Failed to create simple poll object.\n");
goto cleanup;
}
int error;
client = avahi_client_new(avahi_simple_poll_get(simple_poll), 0, discover_client_callback, NULL, &error);
if (!client) {
fprintf(stderr, "Failed to create client: %s\n", avahi_strerror(error));
goto cleanup;
}
if (!(sb = avahi_service_browser_new(client, AVAHI_IF_UNSPEC, AVAHI_PROTO_UNSPEC, "_nvstream._tcp", NULL, 0, discover_browse_callback, dest))) {
fprintf(stderr, "Failed to create service browser: %s\n", avahi_strerror(avahi_client_errno(client)));
goto cleanup;
}
avahi_simple_poll_loop(simple_poll);
cleanup:
if (sb)
avahi_service_browser_free(sb);
if (client)
avahi_client_free(client);
if (simple_poll)
avahi_simple_poll_free(simple_poll);
}

View File

@@ -1,104 +0,0 @@
/*
* This file is part of Moonlight Embedded.
*
* Copyright (C) 2015 Iwan Timmer
*
* Moonlight 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.
*
* Moonlight 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 Moonlight; if not, see <http://www.gnu.org/licenses/>.
*/
#include "http.h"
#include <string.h>
#include <curl/curl.h>
static CURL *curl;
static const char *pCertFile = "./client.pem";
static const char *pKeyFile = "./key.pem";
static size_t _write_curl(void *contents, size_t size, size_t nmemb, void *userp)
{
size_t realsize = size * nmemb;
struct http_data *mem = (struct http_data *)userp;
mem->memory = realloc(mem->memory, mem->size + realsize + 1);
if(mem->memory == NULL) {
fprintf(stderr, "Not enough memory\n");
exit(EXIT_FAILURE);
}
memcpy(&(mem->memory[mem->size]), contents, realsize);
mem->size += realsize;
mem->memory[mem->size] = 0;
return realsize;
}
void http_init() {
curl = curl_easy_init();
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L);
curl_easy_setopt(curl, CURLOPT_SSLENGINE_DEFAULT, 1L);
curl_easy_setopt(curl, CURLOPT_SSLCERTTYPE,"PEM");
curl_easy_setopt(curl, CURLOPT_SSLCERT, pCertFile);
curl_easy_setopt(curl, CURLOPT_SSLKEYTYPE, "PEM");
curl_easy_setopt(curl, CURLOPT_SSLKEY, pKeyFile);
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, _write_curl);
curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1L);
}
int http_request(char* url, struct http_data* data) {
curl_easy_setopt(curl, CURLOPT_WRITEDATA, data);
curl_easy_setopt(curl, CURLOPT_URL, url);
if (data->size > 0) {
free(data->memory);
data->memory = malloc(1);
if(data->memory == NULL) {
fprintf(stderr, "Not enough memory\n");
exit(EXIT_FAILURE);
}
data->size = 0;
}
CURLcode res = curl_easy_perform(curl);
if(res != CURLE_OK) {
fprintf(stderr, "Connection failed: %s\n", curl_easy_strerror(res));
exit(EXIT_FAILURE);
}
return 0;
}
void http_cleanup() {
curl_easy_cleanup(curl);
}
struct http_data* http_create_data() {
struct http_data* data = malloc(sizeof(struct http_data));
data->memory = malloc(1);
if(data->memory == NULL) {
fprintf(stderr, "Not enough memory\n");
exit(EXIT_FAILURE);
}
data->size = 0;
return data;
}
void http_free_data(struct http_data* data) {
free(data->memory);
free(data);
}

103
src/input/cec.c Normal file
View File

@@ -0,0 +1,103 @@
/*
* This file is part of Moonlight Embedded.
*
* Copyright (C) 2015 Iwan Timmer
*
* Moonlight 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.
*
* Moonlight 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 Moonlight; if not, see <http://www.gnu.org/licenses/>.
*/
#ifdef HAVE_LIBCEC
#include <ceccloader.h>
static libcec_configuration g_config;
static char g_strPort[50] = { 0 };
static libcec_interface_t g_iface;
static ICECCallbacks g_callbacks;
static int on_cec_keypress(void* userdata, const cec_keypress key) {
char value;
switch (key.keycode) {
case CEC_USER_CONTROL_CODE_UP:
value = KEY_UP;
break;
case CEC_USER_CONTROL_CODE_DOWN:
value = KEY_DOWN;
break;
case CEC_USER_CONTROL_CODE_LEFT:
value = KEY_LEFT;
break;
case CEC_USER_CONTROL_CODE_RIGHT:
value = KEY_RIGHT;
break;
case CEC_USER_CONTROL_CODE_ENTER:
case CEC_USER_CONTROL_CODE_SELECT:
value = KEY_ENTER;
break;
case CEC_USER_CONTROL_CODE_ROOT_MENU:
value = KEY_TAB;
break;
case CEC_USER_CONTROL_CODE_AN_RETURN:
case CEC_USER_CONTROL_CODE_EXIT:
value = KEY_ESC;
break;
default:
value = 0;
break;
}
if (value != 0) {
short code = 0x80 << 8 | keyCodes[value];
LiSendKeyboardEvent(code, (key.duration > 0)?KEY_ACTION_UP:KEY_ACTION_DOWN, 0);
}
}
void init_cec() {
libcecc_reset_configuration(&g_config);
g_config.clientVersion = LIBCEC_VERSION_CURRENT;
g_config.bActivateSource = 0;
g_callbacks.CBCecKeyPress = &on_cec_keypress;
g_config.callbacks = &g_callbacks;
snprintf(g_config.strDeviceName, sizeof(g_config.strDeviceName), "Moonlight");
g_config.callbacks = &g_callbacks;
g_config.deviceTypes.types[0] = CEC_DEVICE_TYPE_PLAYBACK_DEVICE;
if (libcecc_initialise(&g_config, &g_iface, NULL) != 1) {
fprintf(stderr, "Failed to initialize libcec interface\n");
fflush(stderr);
return;
}
g_iface.init_video_standalone(g_iface.connection);
cec_adapter devices[10];
int8_t iDevicesFound = g_iface.find_adapters(g_iface.connection, devices, sizeof(devices) / sizeof(devices), NULL);
if (iDevicesFound <= 0) {
fprintf(stderr, "No CEC devices found\n");
fflush(stderr);
libcecc_destroy(&g_iface);
return;
}
strcpy(g_strPort, devices[0].comm);
if (!g_iface.open(g_iface.connection, g_strPort, 5000)) {
fprintf(stderr, "Unable to open the device on port %s\n", g_strPort);
fflush(stderr);
libcecc_destroy(&g_iface);
return;
}
g_iface.set_active_source(g_iface.connection, g_config.deviceTypes.types[0]);
}
#endif /* HAVE_LIBCEC */

View File

@@ -1,6 +1,8 @@
/*
* This file is part of Moonlight Embedded.
*
* Copyright (C) 2015 Iwan Timmer
*
* Moonlight 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
@@ -15,6 +17,4 @@
* along with Moonlight; if not, see <http://www.gnu.org/licenses/>.
*/
#define MAX_ADDRESS_SIZE 40
void discover_server(char* dest);
void init_cec();

View File

@@ -17,27 +17,22 @@
* along with Moonlight; if not, see <http://www.gnu.org/licenses/>.
*/
#include "../loop.h"
#include "../global.h"
#include "keyboard.h"
#include "mapping.h"
#include "global.h"
#include "libevdev/libevdev.h"
#include "limelight-common/Limelight.h"
#ifdef HAVE_LIBCEC
#include <ceccloader.h>
#endif
#include <libudev.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <signal.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/signalfd.h>
#include <fcntl.h>
#include <poll.h>
#include <limits.h>
@@ -55,7 +50,6 @@ struct input_device {
struct libevdev *dev;
struct mapping map;
int fd;
int fdindex;
char modifiers;
__s32 mouseDeltaX, mouseDeltaY, mouseScroll;
short controllerId;
@@ -68,112 +62,22 @@ struct input_device {
struct input_abs_parms dpadxParms, dpadyParms;
};
static struct pollfd* fds = NULL;
static struct input_device* devices = NULL;
static int numDevices = 0, numFds = 0;
static int numDevices = 0;
static int assignedControllerIds = 0;
static short* currentKey;
static short* currentAbs;
static bool* currentReverse;
static bool autoadd;
static char* defaultMapfile;
static struct udev *udev;
static struct udev_monitor *udev_mon;
static int udev_fdindex;
static int sig_fdindex;
static bool grabbingDevices;
#define QUIT_MODIFIERS (MODIFIER_SHIFT|MODIFIER_ALT|MODIFIER_CTRL)
#define QUIT_KEY KEY_Q
#ifdef HAVE_LIBCEC
static libcec_configuration g_config;
static char g_strPort[50] = { 0 };
static libcec_interface_t g_iface;
static ICECCallbacks g_callbacks;
static bool (*handler) (struct input_event*, struct input_device*);
static int on_cec_keypress(void* userdata, const cec_keypress key) {
char value;
switch (key.keycode) {
case CEC_USER_CONTROL_CODE_UP:
value = KEY_UP;
break;
case CEC_USER_CONTROL_CODE_DOWN:
value = KEY_DOWN;
break;
case CEC_USER_CONTROL_CODE_LEFT:
value = KEY_LEFT;
break;
case CEC_USER_CONTROL_CODE_RIGHT:
value = KEY_RIGHT;
break;
case CEC_USER_CONTROL_CODE_ENTER:
case CEC_USER_CONTROL_CODE_SELECT:
value = KEY_ENTER;
break;
case CEC_USER_CONTROL_CODE_ROOT_MENU:
value = KEY_TAB;
break;
case CEC_USER_CONTROL_CODE_AN_RETURN:
case CEC_USER_CONTROL_CODE_EXIT:
value = KEY_ESC;
break;
default:
value = 0;
break;
}
if (value != 0) {
short code = 0x80 << 8 | keyCodes[value];
LiSendKeyboardEvent(code, (key.duration > 0)?KEY_ACTION_UP:KEY_ACTION_DOWN, 0);
}
}
static void init_cec() {
libcecc_reset_configuration(&g_config);
g_config.clientVersion = LIBCEC_VERSION_CURRENT;
g_config.bActivateSource = 0;
g_callbacks.CBCecKeyPress = &on_cec_keypress;
g_config.callbacks = &g_callbacks;
snprintf(g_config.strDeviceName, sizeof(g_config.strDeviceName), "Moonlight");
g_config.callbacks = &g_callbacks;
g_config.deviceTypes.types[0] = CEC_DEVICE_TYPE_PLAYBACK_DEVICE;
if (libcecc_initialise(&g_config, &g_iface, NULL) != 1) {
fprintf(stderr, "Failed to initialize libcec interface\n");
fflush(stderr);
return;
}
g_iface.init_video_standalone(g_iface.connection);
cec_adapter devices[10];
int8_t iDevicesFound = g_iface.find_adapters(g_iface.connection, devices, sizeof(devices) / sizeof(devices), NULL);
if (iDevicesFound <= 0) {
fprintf(stderr, "No CEC devices found\n");
fflush(stderr);
libcecc_destroy(&g_iface);
return;
}
strcpy(g_strPort, devices[0].comm);
if (!g_iface.open(g_iface.connection, g_strPort, 5000)) {
fprintf(stderr, "Unable to open the device on port %s\n", g_strPort);
fflush(stderr);
libcecc_destroy(&g_iface);
return;
}
g_iface.set_active_source(g_iface.connection, g_config.deviceTypes.types[0]);
}
#endif
static void input_init_parms(struct input_device *dev, struct input_abs_parms *parms, int code) {
static void evdev_init_parms(struct input_device *dev, struct input_abs_parms *parms, int code) {
parms->flat = libevdev_get_abs_flat(dev->dev, code);
parms->min = libevdev_get_abs_minimum(dev->dev, code);
parms->max = libevdev_get_abs_maximum(dev->dev, code);
@@ -182,151 +86,19 @@ static void input_init_parms(struct input_device *dev, struct input_abs_parms *p
parms->diff = parms->max - parms->min;
}
void input_create(const char* device, char* mapFile) {
int fd = open(device, O_RDONLY|O_NONBLOCK);
if (fd <= 0) {
fprintf(stderr, "Failed to open device %s\n", device);
fflush(stderr);
return;
}
int dev = numDevices;
int fdindex = numFds;
numDevices++;
numFds++;
if (fds == NULL) {
fds = malloc(sizeof(struct pollfd));
devices = malloc(sizeof(struct input_device));
} else {
fds = realloc(fds, sizeof(struct pollfd)*numFds);
devices = realloc(devices, sizeof(struct input_device)*numDevices);
}
if (fds == NULL || devices == NULL) {
fprintf(stderr, "Not enough memory\n");
exit(EXIT_FAILURE);
}
memset(&devices[dev], 0, sizeof(devices[0]));
devices[dev].fd = fd;
devices[dev].dev = libevdev_new();
libevdev_set_fd(devices[dev].dev, devices[dev].fd);
devices[dev].fdindex = fdindex;
fds[fdindex].fd = devices[dev].fd;
fds[fdindex].events = POLLIN;
if (mapFile != NULL)
mapping_load(mapFile, &(devices[dev].map));
devices[dev].controllerId = -1;
input_init_parms(&devices[dev], &(devices[dev].xParms), devices[dev].map.abs_x);
input_init_parms(&devices[dev], &(devices[dev].yParms), devices[dev].map.abs_y);
input_init_parms(&devices[dev], &(devices[dev].zParms), devices[dev].map.abs_z);
input_init_parms(&devices[dev], &(devices[dev].rxParms), devices[dev].map.abs_rx);
input_init_parms(&devices[dev], &(devices[dev].ryParms), devices[dev].map.abs_ry);
input_init_parms(&devices[dev], &(devices[dev].rzParms), devices[dev].map.abs_rz);
input_init_parms(&devices[dev], &(devices[dev].dpadxParms), devices[dev].map.abs_dpad_x);
input_init_parms(&devices[dev], &(devices[dev].dpadyParms), devices[dev].map.abs_dpad_y);
if (grabbingDevices) {
if (ioctl(fd, EVIOCGRAB, 1) < 0) {
fprintf(stderr, "EVIOCGRAB failed with error %d\n", errno);
}
}
}
static void input_remove(int devindex) {
static void evdev_remove(int devindex) {
numDevices--;
numFds--;
if (devices[devindex].controllerId >= 0)
assignedControllerIds &= ~(1 << devices[devindex].controllerId);
int fdindex = devices[devindex].fdindex;
if (fdindex != numFds && numFds > 0) {
memcpy(&fds[fdindex], &fds[numFds], sizeof(struct pollfd));
if (numFds == udev_fdindex)
udev_fdindex = fdindex;
else if (numFds == sig_fdindex)
sig_fdindex = fdindex;
else {
for (int i=0;i<numDevices;i++) {
if (devices[i].fdindex == numFds) {
devices[i].fdindex = fdindex;
break;
}
}
}
}
if (devindex != numDevices && numDevices > 0)
memcpy(&devices[devindex], &devices[numDevices], sizeof(struct input_device));
fprintf(stderr, "Removed input device\n");
}
void input_init(char* mapfile) {
#ifdef HAVE_LIBCEC
init_cec();
#endif
udev = udev_new();
if (!udev) {
fprintf(stderr, "Can't create udev\n");
exit(1);
}
autoadd = (numDevices == 0);
if (autoadd) {
struct udev_enumerate *enumerate = udev_enumerate_new(udev);
udev_enumerate_add_match_subsystem(enumerate, "input");
udev_enumerate_scan_devices(enumerate);
struct udev_list_entry *devices = udev_enumerate_get_list_entry(enumerate);
struct udev_list_entry *dev_list_entry;
udev_list_entry_foreach(dev_list_entry, devices) {
const char *path = udev_list_entry_get_name(dev_list_entry);
struct udev_device *dev = udev_device_new_from_syspath(udev, path);
const char *devnode = udev_device_get_devnode(dev);
int id;
if (devnode != NULL && sscanf(devnode, "/dev/input/event%d", &id) == 1) {
input_create(devnode, mapfile);
}
udev_device_unref(dev);
}
udev_enumerate_unref(enumerate);
}
udev_mon = udev_monitor_new_from_netlink(udev, "udev");
udev_monitor_filter_add_match_subsystem_devtype(udev_mon, "input", NULL);
udev_monitor_enable_receiving(udev_mon);
udev_fdindex = numFds++;
sig_fdindex = numFds++;
if (fds == NULL)
fds = malloc(sizeof(struct pollfd)*numFds);
else
fds = realloc(fds, sizeof(struct pollfd)*numFds);
if (fds == NULL) {
fprintf(stderr, "Not enough memory\n");
exit(EXIT_FAILURE);
}
defaultMapfile = mapfile;
fds[udev_fdindex].fd = udev_monitor_get_fd(udev_mon);
fds[udev_fdindex].events = POLLIN;
main_thread_id = pthread_self();
}
void input_destroy() {
udev_unref(udev);
}
static short input_convert_value(struct input_event *ev, struct input_device *dev, struct input_abs_parms *parms, bool reverse) {
static short evdev_convert_value(struct input_event *ev, struct input_device *dev, struct input_abs_parms *parms, bool reverse) {
if (abs(ev->value - parms->avg) < parms->flat)
return 0;
else if (ev->value > parms->max)
@@ -339,7 +111,7 @@ static short input_convert_value(struct input_event *ev, struct input_device *de
return (ev->value - (ev->value>parms->avg?parms->flat*2:0) - parms->min) * (SHRT_MAX-SHRT_MIN) / (parms->max-parms->min-parms->flat*2) - SHRT_MIN;
}
static char input_convert_value_byte(struct input_event *ev, struct input_device *dev, struct input_abs_parms *parms) {
static char evdev_convert_value_byte(struct input_event *ev, struct input_device *dev, struct input_abs_parms *parms) {
if (abs(ev->value-parms->min)<parms->flat)
return 0;
else if (ev->value>parms->max)
@@ -350,7 +122,7 @@ static char input_convert_value_byte(struct input_event *ev, struct input_device
}
}
static int input_convert_value_direction(struct input_event *ev, struct input_device *dev, struct input_abs_parms *parms, bool reverse) {
static int evdev_convert_value_direction(struct input_event *ev, struct input_device *dev, struct input_abs_parms *parms, bool reverse) {
if (ev->value > (parms->avg+parms->range/4))
return reverse?-1:1;
else if (ev->value < (parms->avg-parms->range/4))
@@ -359,7 +131,7 @@ static int input_convert_value_direction(struct input_event *ev, struct input_de
return 0;
}
static bool input_handle_event(struct input_event *ev, struct input_device *dev) {
static bool evdev_handle_event(struct input_event *ev, struct input_device *dev) {
bool gamepadModified = false;
switch (ev->type) {
@@ -505,19 +277,19 @@ static bool input_handle_event(struct input_event *ev, struct input_device *dev)
case EV_ABS:
gamepadModified = true;
if (ev->code == dev->map.abs_x)
dev->leftStickX = input_convert_value(ev, dev, &dev->xParms, dev->map.reverse_x);
dev->leftStickX = evdev_convert_value(ev, dev, &dev->xParms, dev->map.reverse_x);
else if (ev->code == dev->map.abs_y)
dev->leftStickY = input_convert_value(ev, dev, &dev->yParms, dev->map.reverse_y);
dev->leftStickY = evdev_convert_value(ev, dev, &dev->yParms, dev->map.reverse_y);
else if (ev->code == dev->map.abs_rx)
dev->rightStickX = input_convert_value(ev, dev, &dev->rxParms, dev->map.reverse_rx);
dev->rightStickX = evdev_convert_value(ev, dev, &dev->rxParms, dev->map.reverse_rx);
else if (ev->code == dev->map.abs_ry)
dev->rightStickY = input_convert_value(ev, dev, &dev->ryParms, dev->map.reverse_ry);
dev->rightStickY = evdev_convert_value(ev, dev, &dev->ryParms, dev->map.reverse_ry);
else if (ev->code == dev->map.abs_z)
dev->leftTrigger = input_convert_value_byte(ev, dev, &dev->zParms);
dev->leftTrigger = evdev_convert_value_byte(ev, dev, &dev->zParms);
else if (ev->code == dev->map.abs_rz)
dev->rightTrigger = input_convert_value_byte(ev, dev, &dev->rzParms);
dev->rightTrigger = evdev_convert_value_byte(ev, dev, &dev->rzParms);
else if (ev->code == dev->map.abs_dpad_x) {
int dir = input_convert_value_direction(ev, dev, &dev->dpadxParms, dev->map.reverse_dpad_x);
int dir = evdev_convert_value_direction(ev, dev, &dev->dpadxParms, dev->map.reverse_dpad_x);
if (dir == 1) {
dev->buttonFlags |= RIGHT_FLAG;
dev->buttonFlags &= ~LEFT_FLAG;
@@ -529,7 +301,7 @@ static bool input_handle_event(struct input_event *ev, struct input_device *dev)
dev->buttonFlags |= LEFT_FLAG;
}
} else if (ev->code == dev->map.abs_dpad_y) {
int dir = input_convert_value_direction(ev, dev, &dev->dpadyParms, dev->map.reverse_dpad_y);
int dir = evdev_convert_value_direction(ev, dev, &dev->dpadyParms, dev->map.reverse_dpad_y);
if (dir == 1) {
dev->buttonFlags |= DOWN_FLAG;
dev->buttonFlags &= ~UP_FLAG;
@@ -550,7 +322,7 @@ static bool input_handle_event(struct input_event *ev, struct input_device *dev)
return true;
}
static bool input_handle_mapping_event(struct input_event *ev, struct input_device *dev) {
static bool evdev_handle_mapping_event(struct input_event *ev, struct input_device *dev) {
switch (ev->type) {
case EV_KEY:
if (currentKey != NULL) {
@@ -563,7 +335,7 @@ static bool input_handle_mapping_event(struct input_event *ev, struct input_devi
case EV_ABS:
if (currentAbs != NULL) {
struct input_abs_parms parms;
input_init_parms(dev, &parms, ev->code);
evdev_init_parms(dev, &parms, ev->code);
if (ev->value > parms.avg + parms.range/2) {
*currentAbs = ev->code;
@@ -579,104 +351,110 @@ static bool input_handle_mapping_event(struct input_event *ev, struct input_devi
return true;
}
static void input_drain(void) {
static void evdev_drain(void) {
for (int i = 0; i < numDevices; i++) {
struct input_event ev;
while (libevdev_next_event(devices[i].dev, LIBEVDEV_READ_FLAG_NORMAL, &ev) >= 0);
}
}
static bool input_poll(bool (*handler) (struct input_event*, struct input_device*)) {
// Block signals that are handled gracefully by the input polling code. This
// is done at the last moment to allow Ctrl+C to work until everything
// is ready to go.
sigset_t sigset;
sigemptyset(&sigset);
sigaddset(&sigset, SIGHUP);
sigaddset(&sigset, SIGTERM);
sigaddset(&sigset, SIGINT);
sigaddset(&sigset, SIGQUIT);
sigprocmask(SIG_BLOCK, &sigset, NULL);
fds[sig_fdindex].fd = signalfd(-1, &sigset, 0);
fds[sig_fdindex].events = POLLIN | POLLERR | POLLHUP;
while (poll(fds, numFds, -1)) {
if (fds[udev_fdindex].revents > 0) {
struct udev_device *dev = udev_monitor_receive_device(udev_mon);
const char *action = udev_device_get_action(dev);
if (action != NULL) {
if (autoadd && strcmp("add", action) == 0) {
const char *devnode = udev_device_get_devnode(dev);
int id;
if (devnode != NULL && sscanf(devnode, "/dev/input/event%d", &id) == 1) {
input_create(devnode, defaultMapfile);
}
static int evdev_handle(int fd) {
for (int i=0;i<numDevices;i++) {
if (devices[i].fd = fd) {
int rc;
struct input_event ev;
while ((rc = libevdev_next_event(devices[i].dev, LIBEVDEV_READ_FLAG_NORMAL, &ev)) >= 0) {
if (rc == LIBEVDEV_READ_STATUS_SYNC)
fprintf(stderr, "Error: cannot keep up\n");
else if (rc == LIBEVDEV_READ_STATUS_SUCCESS) {
if (!handler(&ev, &devices[i]))
return LOOP_RETURN;
}
udev_device_unref(dev);
}
} else if (fds[sig_fdindex].revents > 0) {
struct signalfd_siginfo info;
read(fds[sig_fdindex].fd, &info, sizeof(info));
switch (info.ssi_signo) {
case SIGINT:
case SIGTERM:
case SIGQUIT:
case SIGHUP:
return false;
}
}
for (int i=0;i<numDevices;i++) {
if (fds[devices[i].fdindex].revents > 0) {
int rc;
struct input_event ev;
while ((rc = libevdev_next_event(devices[i].dev, LIBEVDEV_READ_FLAG_NORMAL, &ev)) >= 0) {
if (rc == LIBEVDEV_READ_STATUS_SYNC)
fprintf(stderr, "Error: cannot keep up\n");
else if (rc == LIBEVDEV_READ_STATUS_SUCCESS) {
if (!handler(&ev, &devices[i]))
return true;
}
}
if (rc == -ENODEV) {
input_remove(i);
} else if (rc != -EAGAIN && rc < 0) {
fprintf(stderr, "Error: %s\n", strerror(-rc));
exit(EXIT_FAILURE);
}
if (rc == -ENODEV) {
evdev_remove(i);
} else if (rc != -EAGAIN && rc < 0) {
fprintf(stderr, "Error: %s\n", strerror(-rc));
exit(EXIT_FAILURE);
}
}
}
return false;
return LOOP_OK;
}
static void input_map_key(char* keyName, short* key) {
void evdev_create(const char* device, char* mapFile) {
int fd = open(device, O_RDONLY|O_NONBLOCK);
if (fd <= 0) {
fprintf(stderr, "Failed to open device %s\n", device);
fflush(stderr);
return;
}
int dev = numDevices;
numDevices++;
if (devices == NULL) {
devices = malloc(sizeof(struct input_device));
} else {
devices = realloc(devices, sizeof(struct input_device)*numDevices);
}
if (devices == NULL) {
fprintf(stderr, "Not enough memory\n");
exit(EXIT_FAILURE);
}
memset(&devices[dev], 0, sizeof(devices[0]));
devices[dev].fd = fd;
devices[dev].dev = libevdev_new();
libevdev_set_fd(devices[dev].dev, devices[dev].fd);
if (mapFile != NULL)
mapping_load(mapFile, &(devices[dev].map));
devices[dev].controllerId = -1;
evdev_init_parms(&devices[dev], &(devices[dev].xParms), devices[dev].map.abs_x);
evdev_init_parms(&devices[dev], &(devices[dev].yParms), devices[dev].map.abs_y);
evdev_init_parms(&devices[dev], &(devices[dev].zParms), devices[dev].map.abs_z);
evdev_init_parms(&devices[dev], &(devices[dev].rxParms), devices[dev].map.abs_rx);
evdev_init_parms(&devices[dev], &(devices[dev].ryParms), devices[dev].map.abs_ry);
evdev_init_parms(&devices[dev], &(devices[dev].rzParms), devices[dev].map.abs_rz);
evdev_init_parms(&devices[dev], &(devices[dev].dpadxParms), devices[dev].map.abs_dpad_x);
evdev_init_parms(&devices[dev], &(devices[dev].dpadyParms), devices[dev].map.abs_dpad_y);
if (grabbingDevices) {
if (ioctl(fd, EVIOCGRAB, 1) < 0) {
fprintf(stderr, "EVIOCGRAB failed with error %d\n", errno);
}
}
loop_add_fd(devices[dev].fd, &evdev_handle, POLLIN);
}
static void evdev_map_key(char* keyName, short* key) {
printf("Press %s\n", keyName);
currentKey = key;
currentAbs = NULL;
*key = -1;
if (!input_poll(input_handle_mapping_event))
exit(1);
loop_main();
usleep(250000);
input_drain();
evdev_drain();
}
static void input_map_abs(char* keyName, short* abs, bool* reverse) {
static void evdev_map_abs(char* keyName, short* abs, bool* reverse) {
printf("Move %s\n", keyName);
currentKey = NULL;
currentAbs = abs;
currentReverse = reverse;
*abs = -1;
if (!input_poll(input_handle_mapping_event))
exit(1);
loop_main();
usleep(250000);
input_drain();
evdev_drain();
}
static void input_map_abskey(char* keyName, short* key, short* abs, bool* reverse) {
static void evdev_map_abskey(char* keyName, short* key, short* abs, bool* reverse) {
printf("Press %s\n", keyName);
currentKey = key;
currentAbs = abs;
@@ -684,54 +462,55 @@ static void input_map_abskey(char* keyName, short* key, short* abs, bool* revers
*key = -1;
*abs = -1;
*currentReverse = false;
if (!input_poll(input_handle_mapping_event))
exit(1);
loop_main();
usleep(250000);
input_drain();
evdev_drain();
}
void input_map(char* fileName) {
void evdev_map(char* fileName) {
struct mapping map;
input_map_abs("Left Stick Right", &(map.abs_x), &(map.reverse_x));
input_map_abs("Left Stick Up", &(map.abs_y), &(map.reverse_y));
input_map_key("Left Stick Button", &(map.btn_thumbl));
handler = evdev_handle_mapping_event;
input_map_abs("Right Stick Right", &(map.abs_rx), &(map.reverse_rx));
input_map_abs("Right Stick Up", &(map.abs_ry), &(map.reverse_ry));
input_map_key("Right Stick Button", &(map.btn_thumbr));
evdev_map_abs("Left Stick Right", &(map.abs_x), &(map.reverse_x));
evdev_map_abs("Left Stick Up", &(map.abs_y), &(map.reverse_y));
evdev_map_key("Left Stick Button", &(map.btn_thumbl));
input_map_abskey("D-Pad Right", &(map.btn_dpad_right), &(map.abs_dpad_x), &(map.reverse_dpad_x));
evdev_map_abs("Right Stick Right", &(map.abs_rx), &(map.reverse_rx));
evdev_map_abs("Right Stick Up", &(map.abs_ry), &(map.reverse_ry));
evdev_map_key("Right Stick Button", &(map.btn_thumbr));
evdev_map_abskey("D-Pad Right", &(map.btn_dpad_right), &(map.abs_dpad_x), &(map.reverse_dpad_x));
if (map.btn_dpad_right >= 0)
input_map_key("D-Pad Left", &(map.btn_dpad_left));
evdev_map_key("D-Pad Left", &(map.btn_dpad_left));
else
map.btn_dpad_left = -1;
input_map_abskey("D-Pad Down", &(map.btn_dpad_down), &(map.abs_dpad_y), &(map.reverse_dpad_y));
evdev_map_abskey("D-Pad Down", &(map.btn_dpad_down), &(map.abs_dpad_y), &(map.reverse_dpad_y));
if (map.btn_dpad_down >= 0)
input_map_key("D-Pad Up", &(map.btn_dpad_up));
evdev_map_key("D-Pad Up", &(map.btn_dpad_up));
else
map.btn_dpad_up = -1;
input_map_key("Button X (1)", &(map.btn_west));
input_map_key("Button A (2)", &(map.btn_south));
input_map_key("Button B (3)", &(map.btn_east));
input_map_key("Button Y (4)", &(map.btn_north));
input_map_key("Back Button", &(map.btn_select));
input_map_key("Start Button", &(map.btn_start));
input_map_key("Special Button", &(map.btn_mode));
evdev_map_key("Button X (1)", &(map.btn_west));
evdev_map_key("Button A (2)", &(map.btn_south));
evdev_map_key("Button B (3)", &(map.btn_east));
evdev_map_key("Button Y (4)", &(map.btn_north));
evdev_map_key("Back Button", &(map.btn_select));
evdev_map_key("Start Button", &(map.btn_start));
evdev_map_key("Special Button", &(map.btn_mode));
bool ignored;
input_map_abskey("Left Trigger", &(map.btn_tl2), &(map.abs_z), &ignored);
input_map_abskey("Right Trigger", &(map.btn_tr2), &(map.abs_rz), &ignored);
evdev_map_abskey("Left Trigger", &(map.btn_tl2), &(map.abs_z), &ignored);
evdev_map_abskey("Right Trigger", &(map.btn_tr2), &(map.abs_rz), &ignored);
input_map_key("Left Bumper", &(map.btn_tl));
input_map_key("Right Bumper", &(map.btn_tr));
evdev_map_key("Left Bumper", &(map.btn_tl));
evdev_map_key("Right Bumper", &(map.btn_tr));
mapping_save(fileName, &map);
}
void input_loop() {
void evdev_start() {
// After grabbing, the only way to quit via the keyboard
// is via the special key combo that the input handling
// code looks for. For this reason, we wait to grab until
@@ -747,9 +526,12 @@ void input_loop() {
grabbingDevices = true;
// Handle input events until the quit combo is pressed
input_poll(input_handle_event);
// Drain any remaining input events so they aren't sent to the terminal
usleep(250000);
input_drain();
}
void evdev_stop() {
evdev_drain();
}
void evdev_init() {
handler = evdev_handle_event;
}

View File

@@ -17,15 +17,10 @@
* along with Moonlight; if not, see <http://www.gnu.org/licenses/>.
*/
#include <stdlib.h>
void evdev_create(const char* device, char* mapFile);
void evdev_loop();
void evdev_map(char* fileName);
struct http_data {
char *memory;
size_t size;
};
void http_init();
int http_request(char* url, struct http_data* data);
struct http_data* http_create_data();
void http_free_data(struct http_data* data);
void evdev_init();
void evdev_start();
void evdev_stop();

97
src/input/udev.c Normal file
View File

@@ -0,0 +1,97 @@
/*
* This file is part of Moonlight Embedded.
*
* Copyright (C) 2015 Iwan Timmer
*
* Moonlight 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.
*
* Moonlight 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 Moonlight; if not, see <http://www.gnu.org/licenses/>.
*/
#include "../loop.h"
#include "evdev.h"
#include <libudev.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <poll.h>
static bool autoadd;
static char* defaultMapfile;
static struct udev *udev;
static struct udev_monitor *udev_mon;
static int udev_fd;
static int udev_handle(int fd) {
struct udev_device *dev = udev_monitor_receive_device(udev_mon);
const char *action = udev_device_get_action(dev);
if (action != NULL) {
if (autoadd && strcmp("add", action) == 0) {
const char *devnode = udev_device_get_devnode(dev);
int id;
if (devnode != NULL && sscanf(devnode, "/dev/input/event%d", &id) == 1) {
evdev_create(devnode, defaultMapfile);
}
}
udev_device_unref(dev);
}
return LOOP_OK;
}
void udev_init(bool autoload, char* mapfile) {
udev = udev_new();
if (!udev) {
fprintf(stderr, "Can't create udev\n");
exit(1);
}
autoadd = autoload;
if (autoload) {
struct udev_enumerate *enumerate = udev_enumerate_new(udev);
udev_enumerate_add_match_subsystem(enumerate, "input");
udev_enumerate_scan_devices(enumerate);
struct udev_list_entry *devices = udev_enumerate_get_list_entry(enumerate);
struct udev_list_entry *dev_list_entry;
udev_list_entry_foreach(dev_list_entry, devices) {
const char *path = udev_list_entry_get_name(dev_list_entry);
struct udev_device *dev = udev_device_new_from_syspath(udev, path);
const char *devnode = udev_device_get_devnode(dev);
int id;
if (devnode != NULL && sscanf(devnode, "/dev/input/event%d", &id) == 1) {
evdev_create(devnode, mapfile);
}
udev_device_unref(dev);
}
udev_enumerate_unref(enumerate);
}
udev_mon = udev_monitor_new_from_netlink(udev, "udev");
udev_monitor_filter_add_match_subsystem_devtype(udev_mon, "input", NULL);
udev_monitor_enable_receiving(udev_mon);
defaultMapfile = mapfile;
int udev_fd = udev_monitor_get_fd(udev_mon);
loop_add_fd(udev_fd, &udev_handle, POLLIN);
}
void evdev_destroy() {
udev_unref(udev);
}

View File

@@ -17,9 +17,5 @@
* along with Moonlight; if not, see <http://www.gnu.org/licenses/>.
*/
void input_init(char* mapfile);
void input_create(char* device, char* mapFile);
void input_loop();
void input_map(char* fileName);
void input_destroy();
void udev_init(bool autoload, char* mapfile);
void evdev_destroy();

113
src/loop.c Normal file
View File

@@ -0,0 +1,113 @@
/*
* This file is part of Moonlight Embedded.
*
* Copyright (C) 2015 Iwan Timmer
*
* Moonlight 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.
*
* Moonlight 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 Moonlight; if not, see <http://www.gnu.org/licenses/>.
*/
#include "loop.h"
#include "global.h"
#include <sys/stat.h>
#include <sys/signalfd.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <poll.h>
#include <signal.h>
#include <string.h>
static struct pollfd* fds = NULL;
static FdHandler* fdHandlers = NULL;
static int numFds = 0;
static int sigFd;
static int loop_sig_handler(int fd) {
struct signalfd_siginfo info;
read(fd, &info, sizeof(info));
switch (info.ssi_signo) {
case SIGINT:
case SIGTERM:
case SIGQUIT:
case SIGHUP:
return LOOP_RETURN;
}
return LOOP_OK;
}
void loop_add_fd(int fd, FdHandler handler, int events) {
int fdindex = numFds;
numFds++;
if (fds == NULL) {
fds = malloc(sizeof(struct pollfd));
fdHandlers = malloc(sizeof(FdHandler*));
} else {
fds = realloc(fds, sizeof(struct pollfd)*numFds);
fdHandlers = realloc(fdHandlers, sizeof(FdHandler*)*numFds);
}
if (fds == NULL || fdHandlers == NULL) {
fprintf(stderr, "Not enough memory\n");
exit(EXIT_FAILURE);
}
fds[fdindex].fd = fd;
fds[fdindex].events = events;
}
void loop_remove_fd(int fd) {
numFds--;
int fdindex;
for (int i=0;i<numFds;i++) {
if (fds[i].fd = fd)
fdindex = i;
break;
}
if (fdindex != numFds && numFds > 0) {
memcpy(&fds[fdindex], &fds[numFds], sizeof(struct pollfd));
memcpy(&fdHandlers[fdindex], &fdHandlers[numFds], sizeof(FdHandler*));
}
}
void loop_main() {
main_thread_id = pthread_self();
sigset_t sigset;
sigemptyset(&sigset);
sigaddset(&sigset, SIGHUP);
sigaddset(&sigset, SIGTERM);
sigaddset(&sigset, SIGINT);
sigaddset(&sigset, SIGQUIT);
sigprocmask(SIG_BLOCK, &sigset, NULL);
sigFd = signalfd(-1, &sigset, 0);
loop_add_fd(sigFd, loop_sig_handler, POLLIN | POLLERR | POLLHUP);
//static bool evdev_poll(bool (*handler) (struct input_event*, struct input_device*)) {
while (poll(fds, numFds, -1)) {
for (int i=0;i<numFds;i++) {
if (fds[i].revents > 0) {
int ret = fdHandlers[i](fds[i].fd);
if (ret == LOOP_RETURN) {
return;
}
break;
}
}
}
}

View File

@@ -16,15 +16,13 @@
* You should have received a copy of the GNU General Public License
* along with Moonlight; if not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <stdio.h>
#define LOOP_RETURN 1
#define LOOP_OK 0
struct app_list {
char* name;
int id;
struct app_list* next;
};
typedef int(*FdHandler)(int fd);
int xml_search(char* data, size_t len, char* node, char** result);
struct app_list* xml_applist(char* data, size_t len);
void loop_add_fd(int fd, FdHandler handler, int events);
void loop_remove_fd(int fd);
void loop_main();

View File

@@ -17,13 +17,17 @@
* along with Moonlight; if not, see <http://www.gnu.org/licenses/>.
*/
#include "loop.h"
#include "client.h"
#include "connection.h"
#include "video.h"
#include "audio.h"
#include "input.h"
#include "discover.h"
#include "input/evdev.h"
#include "input/udev.h"
#include "input/cec.h"
#include "limelight-common/Limelight.h"
#include <stdio.h>
@@ -42,28 +46,55 @@
#define MOONLIGHT_PATH "/moonlight/"
#define USER_PATHS ":~/.moonlight/:./"
static void applist(const char* address) {
struct app_list* list = client_applist(address);
static void applist(PSERVER_DATA server) {
PAPP_LIST list;
if (gs_applist(server, list) != GS_OK) {
fprintf(stderr, "Can't get app list\n");
return;
}
for (int i = 1;list != NULL;i++) {
printf("%d. %s\n", i, list->name);
list = list->next;
}
}
static void stream(STREAM_CONFIGURATION* config, const char* address, const char* app, bool sops, bool localaudio) {
int appId = client_get_app_id(address, app);
static int get_app_id(PSERVER_DATA server, const char *name) {
PAPP_LIST list;
if (gs_applist(server, list) != GS_OK) {
fprintf(stderr, "Can't get app list\n");
return -1;
}
while (list != NULL) {
if (strcmp(list->name, name) == 0)
return list->id;
list = list->next;
}
return -1;
}
static void stream(PSERVER_DATA server, PSTREAM_CONFIGURATION config, const char* app, bool sops, bool localaudio) {
int appId = get_app_id(server, app);
if (appId<0) {
fprintf(stderr, "Can't find app %s\n", app);
exit(-1);
}
client_start_app(config, address, appId, sops, localaudio);
gs_start_app(server, config, appId, sops, localaudio);
video_init();
evdev_init();
#ifdef HAVE_LIBCEC
cec_init();
#endif /* HAVE_LIBCEC */
LiStartConnection(address, config, &connection_callbacks, decoder_callbacks, &audio_callbacks, NULL, 0, client_get_server_version());
LiStartConnection(server->address, config, &connection_callbacks, decoder_callbacks, &audio_callbacks, NULL, 0, server->serverMajorVersion);
input_loop();
evdev_start();
loop_main();
evdev_stop();
LiStopConnection();
}
@@ -138,8 +169,8 @@ char* get_path(char* name) {
return NULL;
}
static void pair_check(void) {
if (!client_is_paired(NULL)) {
static void pair_check(PSERVER_DATA server) {
if (!server->paired) {
fprintf(stderr, "You must pair with the PC first\n");
exit(-1);
}
@@ -213,7 +244,7 @@ int main(int argc, char* argv[]) {
app = optarg;
break;
case 'j':
input_create(optarg, mapping);
evdev_create(optarg, mapping);
inputAdded = true;
mapped = true;
break;
@@ -267,8 +298,8 @@ int main(int argc, char* argv[]) {
perror("No filename for mapping");
exit(-1);
}
input_init(mapping);
input_map(address);
udev_init(!inputAdded, mapping);
evdev_map(address);
exit(0);
}
@@ -279,27 +310,38 @@ int main(int argc, char* argv[]) {
exit(-1);
}
address[0] = 0;
discover_server(address);
gs_discover_server(address);
if (address[0] == 0) {
fprintf(stderr, "Autodiscovery failed. Specify an IP address next time.\n");
exit(-1);
}
}
client_init(address);
PSERVER_DATA server;
if (gs_init(server, address, ".") != GS_OK) {
fprintf(stderr, "Can't connect to server %s\n", address);
exit(-1);
}
if (strcmp("list", action) == 0) {
pair_check();
applist(address);
pair_check(server);
applist(server);
} else if (strcmp("stream", action) == 0) {
input_init(mapping);
pair_check();
stream(&config, address, app, sops, localaudio);
} else if (strcmp("pair", action) == 0)
client_pair(address);
else if (strcmp("quit", action) == 0) {
pair_check();
client_quit_app(address);
udev_init(!inputAdded, mapping);
pair_check(server);
stream(server, &config, app, sops, localaudio);
} else if (strcmp("pair", action) == 0) {
char pin[5];
sprintf(pin, "%d%d%d%d", (int)random() % 10, (int)random() % 10, (int)random() % 10, (int)random() % 10);
printf("Please enter the following PIN on the target PC: %s\n", pin);
if (gs_pair(server, &pin[0]) != GS_OK) {
fprintf("Failed to pair to server: %s\n", gs_error);
} else {
printf("Succesfully paired\n");
}
} else if (strcmp("quit", action) == 0) {
pair_check(server);
gs_quit_app(server);
} else
fprintf(stderr, "%s is not a valid action\n", action);
}

View File

@@ -1,176 +0,0 @@
/*
* Moonlight 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.
*
* Moonlight 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 Moonlight; if not, see <http://www.gnu.org/licenses/>.
*/
#include "mkcert.h"
#include <stdio.h>
#include <stdlib.h>
#include <openssl/pem.h>
#include <openssl/conf.h>
#include <openssl/pkcs12.h>
#ifndef OPENSSL_NO_ENGINE
#include <openssl/engine.h>
#endif
static const int NUM_BITS = 2048;
static const int SERIAL = 0;
static const int NUM_YEARS = 10;
int mkcert(X509 **x509p, EVP_PKEY **pkeyp, int bits, int serial, int years);
int add_ext(X509 *cert, int nid, char *value);
struct CertKeyPair generateCertKeyPair() {
BIO *bio_err;
X509 *x509 = NULL;
EVP_PKEY *pkey = NULL;
PKCS12 *p12 = NULL;
CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON);
bio_err = BIO_new_fp(stderr, BIO_NOCLOSE);
SSLeay_add_all_algorithms();
ERR_load_crypto_strings();
mkcert(&x509, &pkey, NUM_BITS, SERIAL, NUM_YEARS);
p12 = PKCS12_create("limelight", "GameStream", pkey, x509, NULL, 0, 0, 0, 0, 0);
if (p12 == NULL) {
fprintf(stderr, "Error generating a valid PKCS12 certificate.\n");
}
#ifndef OPENSSL_NO_ENGINE
ENGINE_cleanup();
#endif
CRYPTO_cleanup_all_ex_data();
CRYPTO_mem_leaks(bio_err);
BIO_free(bio_err);
return (CertKeyPair){x509, pkey, p12};
}
void freeCertKeyPair(struct CertKeyPair certKeyPair) {
X509_free(certKeyPair.x509);
EVP_PKEY_free(certKeyPair.pkey);
PKCS12_free(certKeyPair.p12);
}
void saveCertKeyPair(const char* certFile, const char* p12File, const char* keyPairFile, CertKeyPair certKeyPair) {
FILE* certFilePtr = fopen(certFile, "w");
FILE* keyPairFilePtr = fopen(keyPairFile, "w");
FILE* p12FilePtr = fopen(p12File, "wb");
//TODO: error check
PEM_write_PrivateKey(keyPairFilePtr, certKeyPair.pkey, NULL, NULL, 0, NULL, NULL);
PEM_write_X509(certFilePtr, certKeyPair.x509);
i2d_PKCS12_fp(p12FilePtr, certKeyPair.p12);
fclose(p12FilePtr);
fclose(certFilePtr);
fclose(keyPairFilePtr);
}
int mkcert(X509 **x509p, EVP_PKEY **pkeyp, int bits, int serial, int years) {
X509 *x;
EVP_PKEY *pk;
RSA *rsa;
X509_NAME *name = NULL;
if (*pkeyp == NULL) {
if ((pk=EVP_PKEY_new()) == NULL) {
abort();
return(0);
}
} else {
pk = *pkeyp;
}
if (*x509p == NULL) {
if ((x = X509_new()) == NULL) {
goto err;
}
} else {
x = *x509p;
}
rsa = RSA_generate_key(bits, RSA_F4, NULL, NULL);
if (!EVP_PKEY_assign_RSA(pk, rsa)) {
abort();
goto err;
}
X509_set_version(x, 2);
ASN1_INTEGER_set(X509_get_serialNumber(x), serial);
X509_gmtime_adj(X509_get_notBefore(x), 0);
X509_gmtime_adj(X509_get_notAfter(x), (long)60*60*24*365*years);
X509_set_pubkey(x, pk);
name = X509_get_subject_name(x);
/* This function creates and adds the entry, working out the
* correct string type and performing checks on its length.
*/
X509_NAME_add_entry_by_txt(name,"CN", MBSTRING_ASC, (unsigned char*)"NVIDIA GameStream Client", -1, -1, 0);
/* Its self signed so set the issuer name to be the same as the
* subject.
*/
X509_set_issuer_name(x, name);
/* Add various extensions: standard extensions */
add_ext(x, NID_basic_constraints, "critical,CA:TRUE");
add_ext(x, NID_key_usage, "critical,keyCertSign,cRLSign");
add_ext(x, NID_subject_key_identifier, "hash");
if (!X509_sign(x, pk, EVP_sha1())) {
goto err;
}
*x509p = x;
*pkeyp = pk;
return(1);
err:
return(0);
}
/* Add extension using V3 code: we can set the config file as NULL
* because we wont reference any other sections.
*/
int add_ext(X509 *cert, int nid, char *value)
{
X509_EXTENSION *ex;
X509V3_CTX ctx;
/* This sets the 'context' of the extensions. */
/* No configuration database */
X509V3_set_ctx_nodb(&ctx);
/* Issuer and subject certs: both the target since it is self signed,
* no request and no CRL
*/
X509V3_set_ctx(&ctx, cert, cert, NULL, NULL, 0);
ex = X509V3_EXT_conf_nid(NULL, &ctx, nid, value);
if (!ex) {
return 0;
}
X509_add_ext(cert, ex, -1);
X509_EXTENSION_free(ex);
return 1;
}

View File

@@ -1,35 +0,0 @@
/*
* Created by Diego Waxemberg on 10/16/14.
* Copyright (c) 2014 Limelight Stream. All rights reserved.
*
* Moonlight 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.
*
* Moonlight 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 Moonlight; if not, see <http://www.gnu.org/licenses/>.
*/
#ifndef Limelight_mkcert_h
#define Limelight_mkcert_h
#include <openssl/x509v3.h>
#include <openssl/pkcs12.h>
typedef struct CertKeyPair {
X509 *x509;
EVP_PKEY *pkey;
PKCS12 *p12;
} CertKeyPair;
struct CertKeyPair generateCertKeyPair();
void freeCertKeyPair(CertKeyPair);
void saveCertKeyPair(const char* certFile, const char* p12File, const char* keyPairFile, CertKeyPair certKeyPair);
#endif

128
src/xml.c
View File

@@ -1,128 +0,0 @@
/*
* This file is part of Moonlight Embedded.
*
* Copyright (C) 2015 Iwan Timmer
*
* Moonlight 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.
*
* Moonlight 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 Moonlight; if not, see <http://www.gnu.org/licenses/>.
*/
#include "xml.h"
#include "expat.h"
#include <string.h>
struct xml_query {
char *memory;
size_t size;
int start;
void* data;
};
static void XMLCALL _xml_start_element(void *userData, const char *name, const char **atts) {
struct xml_query *search = (struct xml_query*) userData;
if (strcmp(search->data, name) == 0)
search->start++;
}
static void XMLCALL _xml_end_element(void *userData, const char *name) {
struct xml_query *search = (struct xml_query*) userData;
if (strcmp(search->data, name) == 0)
search->start--;
}
static void XMLCALL _xml_start_applist_element(void *userData, const char *name, const char **atts) {
struct xml_query *search = (struct xml_query*) userData;
if (strcmp("App", name) == 0) {
struct app_list* app = malloc(sizeof(struct app_list));
if (app == NULL) {
perror("Not enough memory");
exit(EXIT_FAILURE);
}
app->next = (struct app_list*) search->data;
search->data = app;
} else if (strcmp("ID", name) == 0 || strcmp("AppTitle", name) == 0) {
search->memory = malloc(1);
search->size = 0;
search->start = 1;
}
}
static void XMLCALL _xml_end_applist_element(void *userData, const char *name) {
struct xml_query *search = (struct xml_query*) userData;
if (search->start) {
struct app_list* list = (struct app_list*) search->data;
if (strcmp("ID", name) == 0) {
list->id = atoi(search->memory);
free(search->memory);
} else if (strcmp("AppTitle", name) == 0) {
list->name = search->memory;
}
search->start = 0;
}
}
static void XMLCALL _xml_write_data(void *userData, const XML_Char *s, int len) {
struct xml_query *search = (struct xml_query*) userData;
if (search->start > 0) {
search->memory = realloc(search->memory, search->size + len + 1);
if(search->memory == NULL) {
fprintf(stderr, "Not enough memory\n");
exit(EXIT_FAILURE);
}
memcpy(&(search->memory[search->size]), s, len);
search->size += len;
search->memory[search->size] = 0;
}
}
int xml_search(char* data, size_t len, char* node, char** result) {
struct xml_query search;
search.data = node;
search.start = 0;
search.memory = calloc(1, 1);
search.size = 0;
XML_Parser parser = XML_ParserCreate("UTF-8");
XML_SetUserData(parser, &search);
XML_SetElementHandler(parser, _xml_start_element, _xml_end_element);
XML_SetCharacterDataHandler(parser, _xml_write_data);
if (! XML_Parse(parser, data, len, 1)) {
int code = XML_GetErrorCode(parser);
fprintf(stderr, "XML Error: %s\n", XML_ErrorString(code));
return 1;
}
*result = search.memory;
return 0;
}
struct app_list* xml_applist(char* data, size_t len) {
struct xml_query query;
query.memory = calloc(1, 1);
query.size = 0;
query.start = 0;
query.data = NULL;
XML_Parser parser = XML_ParserCreate("UTF-8");
XML_SetUserData(parser, &query);
XML_SetElementHandler(parser, _xml_start_applist_element, _xml_end_applist_element);
XML_SetCharacterDataHandler(parser, _xml_write_data);
if (! XML_Parse(parser, data, len, 1)) {
int code = XML_GetErrorCode(parser);
fprintf(stderr, "XML Error %s\n", XML_ErrorString(code));
exit(-1);
}
return (struct app_list*) query.data;
}