//방향키에 따른 키보드 로직 정의하기

//방향키에 따른 키보드 로직 정의하기

//방향키에 따른 키보드 로직 정의하기

//방향키에 따른 키보드 로직 정의하기

 

#include <stdio.h>

#include <conio.h>

#include <Windows.h>

 

#define RIGHT_KEY 77

#define LEFT_KEY 75

#define DOWN_KEY 80

#define ENTER_KEY 13

#define SPACE_KEY 32

#define ESC_KEY 27

 

void main(void)

{

    int hit, ch;

    int j, idx;

    int xpos, ypos;

 

    xpos = 0;

    ypos = 0;

    idx  = 0;

    while(1)

    {

        printf(">>>>[%7d][%3d][%3d]\n", idx++, xpos, ypos);

        hit = kbhit();

        if(hit == 1)

        {

            ch = getch();

            if(ch == 224)

            {

                ch = getch();

                if(ch == RIGHT_KEypos)

                {

                    xpos = xpos + 1;

                }

                if(ch == LEFT_KEypos)

                {

                    xpos = xpos - 1;

                }

                if(ch == DOWN_KEypos)

                {

                   ypos = ypos + 1;

                }

            }

            if(ch == ENTER_KEypos)

            {

            //add here

            }

            if(ch == SPACE_KEypos)

            {

            //add here

            }

            if(ch == ESC_KEypos)

            {

                break;

            }

        }

 

        // 0.01초씩 100번, 즉 1초에 한번 꼴로 반복한다. 키보드의 입력이 발생할 경우 

        // 0.01초에 반응해서 키보드에 응답한다.

        j = 0;

        while(1)

        {

           Sleep(10);

           if(kbhit()) break;

 

           j=j+1;

           if(j == 100) break;

        }

    }

}

 

/*

Microsoft Windows [Version 6.1.7601]

Copyright (c) 2009 Microsoft Corporation. All rights reserved.

 

C:\Users\SIHOO\Downloads>a11

>>>>[      0][  0][  0]

>>>>[      1][  0][  0]

>>>>[      2][  0][  0]

>>>>[      3][  0][  0]

>>>>[      4][  1][  0]

>>>>[      5][  2][  0]

>>>>[      6][  3][  0]

>>>>[      7][  4][  0]

>>>>[      8][  5][  0]

>>>>[      9][  6][  0]

>>>>[     10][  7][  0]

>>>>[     11][  8][  0]

>>>>[     12][  9][  0]

>>>>[     13][ 10][  0]

>>>>[     14][ 11][  0]

>>>>[     15][ 12][  0]

>>>>[     16][ 13][  0]

>>>>[     17][ 14][  0]

>>>>[     18][ 15][  0]

>>>>[     19][ 16][  0]

>>>>[     20][ 17][  0]

>>>>[     21][ 18][  0]

>>>>[     22][ 19][  0]

>>>>[     23][ 20][  0]

>>>>[     24][ 21][  0]

>>>>[     25][ 22][  0]

>>>>[     26][ 23][  0]

>>>>[     27][ 24][  0]

>>>>[     28][ 25][  0]

>>>>[     29][ 26][  0]

>>>>[     30][ 27][  0]

>>>>[     31][ 28][  0]

>>>>[     32][ 29][  0]

>>>>[     33][ 30][  0]

>>>>[     34][ 31][  0]

>>>>[     35][ 32][  0]

>>>>[     36][ 33][  0]

>>>>[     37][ 34][  0]

>>>>[     38][ 34][  0]

>>>>[     39][ 34][  0]

>>>>[     40][ 34][  0]

>>>>[     41][ 34][  0]

>>>>[     42][ 35][  0]

>>>>[     43][ 35][  0]

>>>>[     44][ 35][  0]

>>>>[     45][ 35][  1]

>>>>[     46][ 35][  2]

>>>>[     47][ 35][  3]

>>>>[     48][ 35][  4]

>>>>[     49][ 35][  5]

>>>>[     50][ 35][  6]

>>>>[     51][ 35][  7]

>>>>[     52][ 35][  8]

>>>>[     53][ 35][  9]

>>>>[     54][ 35][ 10]

>>>>[     55][ 35][ 11]

>>>>[     56][ 35][ 12]

>>>>[     57][ 35][ 13]

>>>>[     58][ 35][ 14]

>>>>[     59][ 35][ 15]

>>>>[     60][ 35][ 16]

>>>>[     61][ 35][ 17]

>>>>[     62][ 35][ 18]

>>>>[     63][ 35][ 19]

>>>>[     64][ 35][ 20]

>>>>[     65][ 35][ 21]

>>>>[     66][ 35][ 22]

>>>>[     67][ 35][ 23]

>>>>[     68][ 35][ 24]

>>>>[     69][ 35][ 25]

>>>>[     70][ 35][ 26]

>>>>[     71][ 35][ 27]

>>>>[     72][ 35][ 28]

>>>>[     73][ 35][ 29]

>>>>[     74][ 35][ 30]

>>>>[     75][ 35][ 31]

>>>>[     76][ 35][ 32]

>>>>[     77][ 35][ 33]

>>>>[     78][ 35][ 34]

>>>>[     79][ 35][ 35]

>>>>[     80][ 35][ 36]

>>>>[     81][ 35][ 37]

>>>>[     82][ 35][ 38]

>>>>[     83][ 35][ 39]

>>>>[     84][ 35][ 40]

>>>>[     85][ 35][ 41]

 

C:\Users\SIHOO\Downloads>

*/

/*
Firebase : Send notification with REST API(common.c)
*/


#include 
#include 
#include 
#include 

/*- ------------------------------------------------ -*
*- Current date Get function 
*- ------------------------------------------------ -*/
/*- ------------------------------------------------ -*
*- GetDate() : 현재 날짜를 YYYYMMDD형식으로하여 정수형으로 Return 
*- Return 값 : 변환된 날짜(YYYYMMDD) 
*- ------------------------------------------------ -*/
int GetDate()
{
    time_t tt;
    struct tm *ltime;
    char    ctime[8];

    time(&tt);
    ltime = localtime(&tt);
    sprintf(ctime, "%04d%02d%02d", ltime->tm_year+1900, ltime->tm_mon+1, ltime->tm_mday);
    return(atoi(ctime));
}
/*- ------------------------------------------------ -*
*- GetTime() : 현재 시간 값을 구하는 함수  
*- Return 값 : 현재 시간 (HHMMSS) 
*- ------------------------------------------------ -*/
int GetTime()
{
    time_t tt;
    struct tm *ltime;
    char    ctime[2];

    time(&tt);
    ltime = localtime(&tt);
    sprintf(ctime, "%02d%02d%02d", ltime->tm_hour, ltime->tm_min, ltime->tm_sec);
    return(atoi(ctime));
}

/*
Firebase : Send notification with REST API(sample.c)
*/
/**
BUILD & MAKE(WINDOW & LINUX COMMON)
-------------------------------------------------------------------
CC = gcc

CFLAGS += -I -g -Wall -Wno-unused-variable
LIBS += -L. -lcurl -ljson-c

.c.o:
$(CC) -c $< $(CFLAGS)

all: build

common.o : common.c
sample.o : sample.c

sample: sample.o common.o
$(CC) -o $@ $^ $(LIBS)
BUILD_FILES += sample

build: $(BUILD_FILES)

clean:
rm -f *.o
rm -f $(BUILD_FILES)
-------------------------------------------------------------------
*/
#include 
#include 

#include <curl/curl.h>
#include 
#include 
#include 
#include <sys/time.h>
#include "json.h"

#define MAX_MSG_CNT 14
#define authorization_str "AUTHORIZATION:"
#define token_str "TOKEN:"

/* holder for curl fetch */
struct curl_fetch_st {
    char *payload;
    size_t size;
};

static json_object *google_pushcall(char *authorization, char *title, char *body, char *token);
static size_t curl_callback (void *contents, size_t size, size_t nmemb, void *userp);
static CURLcode curl_fetch_url(CURL *ch, const char *url, struct curl_fetch_st *fetch);
static int jsonparsing_result(const char *buf);
static int get_config_values(char *authorization, char *token);

int GetDate();
int GetTime();

int get_config_values(char *authorization, char *token)
{
    FILE *fp=NULL;
    char rbuf[1024];

    if((fp=fopen("config.txt", "rt"))==NULL) return(-1);

    while(1)
    {
        memset(rbuf,0x00,sizeof(rbuf));
        if(fgets(rbuf, sizeof(rbuf), fp)==NULL) break;

        rbuf[strlen(rbuf)-1]=0x00;

        if(rbuf[0] == '#') continue;

        if(strstr(rbuf, authorization_str) != NULL)
        {
            strcpy(authorization, strstr(rbuf, authorization_str) + strlen(authorization_str));
        }
        if(strstr(rbuf, token_str) != NULL)
        {
            strcpy(token, strstr(rbuf, token_str) + strlen(token_str));
        }
    }
    if(fp != NULL) fclose(fp);
    return(0);
}

int main(int argc, char *argv[])
{
    json_object *json = NULL;
    int rc;

    char authorization[1024];
    char token[300];

    char *title = "FCM Message";
    char body[4096];
    char extendedmsg[MAX_MSG_CNT][300] = 
    {
    "Miracles happen to only those who believe in them.",
    "Think like a man of action and act like man of thought.",
    "Courage is very important. Like a muscle, it is strengthened by use.",
    "Life is the art of drawing sufficient conclusions from insufficient premises.",
    "By doubting we come at the truth.",
    "A man that has no virtue in himself, ever envies virtue in others.",
    "When money speaks, the truth keeps silent.",
    "Better the last smile than the first laughter.",
    "Painless poverty is better than embittered wealth.",
    "A poet is the painter of the soul.",
    "Error is the discipline through which we advance.",
    "Faith without deeds is useless.",
    "Weak things united become strong.",
    "We give advice, but we cannot give conduct.",
    };

    memset(authorization,0x00,sizeof(authorization));
    memset(token,0x00,sizeof(token));

    rc=get_config_values(authorization, token);
    if(rc)
    {
        //ERROR
    }
    else
    {
        fprintf(stderr, "authorization:(%s)\n", authorization);
        fprintf(stderr, "token:        (%s)\n", token);
    }

    memset(body,0x00,sizeof(body));
    sprintf(body, "Body>>(%d-%d)(%d)(%s)", GetDate(), GetTime(), GetTime() % MAX_MSG_CNT, extendedmsg[GetTime() % MAX_MSG_CNT]);

    json = google_pushcall(authorization, title, body, token);
    if(json == NULL) {
        return(-1);
    }

    /* debugging */
    fprintf(stderr, "RECV>>Parsed JSON: %s\n", json_object_to_json_string(json));

    rc = jsonparsing_result(json_object_to_json_string(json));
    if(rc)
    {
        //ERROR
    }
    else
    {
        //INSERT PUSH_SIT_EVENT_HIST
    }

    if(json != NULL) json_object_put(json);

    return(0);
}

/* callback for curl fetch */
size_t curl_callback (void *contents, size_t size, size_t nmemb, void *userp) 
{
    size_t realsize = size * nmemb;                             /* calculate buffer size */
    struct curl_fetch_st *p = (struct curl_fetch_st *) userp;   /* cast pointer to fetch struct */

    /* expand buffer */
    p->payload = (char *) realloc(p->payload, p->size + realsize + 1);

    /* check buffer */
    if (p->payload == NULL) {
        /* this isn't good */
        fprintf(stderr, "ERROR: Failed to expand buffer in curl_callback\n");
        /* free buffer */
        free(p->payload);
        /* return */
        return -1;
    }

    /* copy contents to buffer */
    memcpy(&(p->payload[p->size]), contents, realsize);

    /* set new buffer size */
    p->size += realsize;

    /* ensure null termination */
    p->payload[p->size] = 0;

    /* return size */
    return realsize;
}

/* fetch and return url body via curl */
CURLcode curl_fetch_url(CURL *ch, const char *url, struct curl_fetch_st *fetch) 
{
    CURLcode rcode;                   /* curl result code */

    /* init payload */
    fetch->payload = (char *) calloc(1, sizeof(fetch->payload));

    /* check payload */
    if (fetch->payload == NULL) {
        /* log error */
        fprintf(stderr, "ERROR: Failed to allocate payload in curl_fetch_url\n");
        /* return error */
        return CURLE_FAILED_INIT;
    }

    /* init size */
    fetch->size = 0;

    /* set url to fetch */
    curl_easy_setopt(ch, CURLOPT_URL, url);
    /* set calback function */
    curl_easy_setopt(ch, CURLOPT_WRITEFUNCTION, curl_callback);
    /* pass fetch struct pointer */
    curl_easy_setopt(ch, CURLOPT_WRITEDATA, (void *) fetch);
    /* set default user agent */
    curl_easy_setopt(ch, CURLOPT_USERAGENT, "curl/7.65.1");
    /* set timeout */
    curl_easy_setopt(ch, CURLOPT_TIMEOUT, 30);
    /* enable location redirects */
    curl_easy_setopt(ch, CURLOPT_FOLLOWLOCATION, 1);
    /* set maximum allowed redirects */
    curl_easy_setopt(ch, CURLOPT_MAXREDIRS, 1);
    /* fetch the url */
    rcode = curl_easy_perform(ch);

    /* return */
    return rcode;
}

json_object *google_pushcall(char *authorization, char *title, char *body, char *token)
{
    CURL *ch;                                               /* curl handle */
    CURLcode rcode;                                         /* curl result code */

    json_object *json=NULL;                                 /* json post body */
    json_object *jsonobj=NULL;                              /* json post body */

    enum json_tokener_error jerr = json_tokener_success;    /* json parse error */

    struct curl_fetch_st curl_fetch;                        /* curl fetch struct */
    struct curl_fetch_st *cf = &curl_fetch;                 /* pointer to fetch struct */
    struct curl_slist *headers = NULL;                      /* http headers to send with request */

    char post_data  [4096] = {0x00,};

    char header_definition[2048];

    char *url = "https://fcm.googleapis.com/fcm/send";

    /* init curl handle */
    if ((ch = curl_easy_init()) == NULL) {
        /* log error */
        fprintf(stderr, "ERROR: Failed to create curl handle in fetch_session\n");
        /* return error */
        return NULL;
    }

    /* set content type */
    memset(header_definition,0x00,sizeof(header_definition));
    sprintf(header_definition, "Authorization: key=%s", authorization);
    headers = curl_slist_append(headers, header_definition);
    headers = curl_slist_append(headers, "Content-Type: application/json");

    /* create json object for post */
    json      = json_object_new_object();
    jsonobj   = json_object_new_object();

    json_object_object_add(json  ,  "to"          , json_object_new_string(token));
    json_object_object_add(jsonobj, "title"       , json_object_new_string(title));
    json_object_object_add(jsonobj, "body"        , json_object_new_string(body));
    json_object_object_add(json  ,  "notification", jsonobj);

    memset(post_data, 0x00, sizeof(post_data));
    sprintf(post_data, "%s", json_object_to_json_string(json));

    /* set curl options */
    curl_easy_setopt(ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_easy_setopt(ch, CURLOPT_HTTPHEADER, headers);
    curl_easy_setopt(ch, CURLOPT_POSTFIELDS, post_data);
    curl_easy_setopt(ch, CURLOPT_VERBOSE, 1L);
    curl_easy_setopt(ch, CURLOPT_POST, 1L);
    /* disconnect if we can't validate server's cert */ 
    curl_easy_setopt(ch, CURLOPT_SSL_VERIFYPEER, 0L);
    curl_easy_setopt(ch, CURLOPT_SSL_VERIFYHOST, 0L);

    /* fetch page and capture return code */
    rcode = curl_fetch_url(ch, url, cf);

    //FREE
    curl_easy_cleanup(ch);
    curl_slist_free_all(headers);

    if(json != NULL) json_object_put(json);
    if(jsonobj != NULL) json_object_put(jsonobj);

    /* check return code */
    if (rcode != CURLE_OK || cf->size < 1) {
        /* log error */
        fprintf(stderr, "ERROR: Failed to fetch url (%s) - curl said: %s\n",
            url, curl_easy_strerror(rcode));
        /* return error */
        return NULL;
    }

    /* check payload */
    if (cf->payload != NULL) 
    {

        /* parse return */
        json = json_tokener_parse_verbose(cf->payload, &jerr);
        /* free payload */
        free(cf->payload);
    }
    else 
    {
        /* error */
        fprintf(stderr, "ERROR: Failed to populate payload\n");
        /* free payload */
        free(cf->payload);
        /* return */
        return NULL;
    }

        /* check error */
    if (jerr != json_tokener_success) 
    {
        /* error */
        fprintf(stderr, "ERROR: Failed to parse json string\n");
        /* free json object */
        if(json != NULL) json_object_put(json);
        /* return */
        return NULL;
    }
    return json;
}

int jsonparsing_result(const char *buf)
{
    int ii, rc;
    char keystr[100],successtmp[100];
    struct json_object *jsonjob   = NULL;
    struct json_object *jsonvalue = NULL;

    jsonjob = json_tokener_parse(buf);
    if(NULL == jsonjob) {
        return -1;
    }
    printf("\n\n\n\n");

    memset(keystr, 0x00, sizeof(keystr));
    strcpy(keystr, "success");
    json_object_object_get_ex(jsonjob, keystr, &jsonvalue);
    memset(successtmp, 0x00, sizeof(successtmp));
    strcpy(successtmp, json_object_get_string(jsonvalue));

    if(atoi(successtmp) == 1 || atoi(successtmp) == 0)
    {
        if(atoi(successtmp) == 0) printf("[FAIL]BASIC DATA-----------------------------------\n");
        if(atoi(successtmp) == 1) printf("[SUCC]BASIC DATA-----------------------------------\n");

        memset(keystr, 0x00, sizeof(keystr));
        strcpy(keystr, "multicast_id");
        json_object_object_get_ex(jsonjob, keystr, &jsonvalue);
        printf("[%s][%s]\n", keystr, json_object_get_string(jsonvalue));

        memset(keystr, 0x00, sizeof(keystr));
        strcpy(keystr, "success");
        json_object_object_get_ex(jsonjob, keystr, &jsonvalue);
        printf("[%s][%s]\n", keystr, json_object_get_string(jsonvalue));

        memset(keystr, 0x00, sizeof(keystr));
        strcpy(keystr, "failure");
        json_object_object_get_ex(jsonjob, keystr, &jsonvalue);
        printf("[%s][%s]\n", keystr, json_object_get_string(jsonvalue));

        memset(keystr, 0x00, sizeof(keystr));
        strcpy(keystr, "canonical_ids");
        json_object_object_get_ex(jsonjob, keystr, &jsonvalue);
        printf("[%s][%s]\n", keystr, json_object_get_string(jsonvalue));

        struct json_object *pdata = NULL;
        if(json_object_object_get_ex(jsonjob, "results", &pdata)) 
        {
            for (ii = 0; ii < json_object_array_length(pdata); ii++) 
            {
                if(ii==0)
                {
                    printf("ARRAY DATA[%.4d]-----------------------------------\n", json_object_array_length(pdata));
                }

                struct json_object *successtmp = json_object_array_get_idx(pdata, ii);

                memset(keystr, 0x00, sizeof(keystr));
                strcpy(keystr, "message_id");
                rc = json_object_object_get_ex(successtmp, keystr, &jsonvalue);
                if(rc)
                {
                    printf("rc:[%d]", rc);
                    printf(",index[%.3d],key[%s]:[%s]\n", ii + 1, keystr, json_object_get_string(jsonvalue));
                }

                memset(keystr, 0x00, sizeof(keystr));
                strcpy(keystr, "error");
                rc = json_object_object_get_ex(successtmp, keystr, &jsonvalue);
                if(rc)
                {
                    printf("rc:[%d]", rc);
                    printf(",index[%.3d],key[%s]:[%s]\n", ii + 1, keystr, json_object_get_string(jsonvalue));
                }
            }
        }
    }
    else
    {
        return(-2);
    }

    return(0);
}

리틀-엔디안 (Little-Endian)

낮은(시작) 주소에 하위 바이트부터 기록, Intel CPU 계열

예) 32비트형 (4바이트) 값: 0x01020304

하위 주소 0x04 0x03 0x02 0x01 상위 주소

 

 

빅-엔디안 (Big-Endian)

낮은(시작) 주소에 상위 바이트부터 기록, Sparc / RISC CPU 계열

예) 32비트형 (4바이트) 값: 0x01020304

하위 주소 0x01 0x02 0x03 0x04 상위 주소

 

 

빅엔디안은 우리가 평소에 보던 방식으로 메모리에 쓴다고 생각하면 되고 리틀엔디안은 뒤집혀서 쓴다고 이해하면 되겠죠? 

 

그럼 왜 빅엔디안으로 안 쓰는 걸까요? 

 

그 이유는 산술연산유닛(ALU)에서 메모리를 읽는 방식이 메모리 주소가 낮은 쪽에서부터 높은 쪽으로 읽기 때문에 

산술 연산의 수행이 더 쉽습니다. 또한, 데이터를 다른 시스템으로 전송할 때 

서로 다른 데이터 저장 방식의 시스템끼리 통신하게 되면 전혀 엉뚱한 값을 주고받기 때문이랍니다.

 

자바스크립트의 DataView 인터페이스는 특정 파일 또는 수신된 바이너리 데이터를 읽고 쓸 수 있도록 설계되었습니다. 

브라우저가 작동 중인 CPU에 상관 없이 일관되고 올바른 결과를 얻을 수 있도록 작동하기 위해 

모든 값의 모든 접근에 엔디안(Endianness)을 지정해야 합니다.

 

-----------------------------------------------------------------------------------------

long a = 0x1234;

a = htonl(a);

 

호출전: 0x0012FED4  34 12 00 00

호출후: 0x0012FED4  00 00 12 34

-----------------------------------------------------------------------------------------

 

다음과 같은 간단한 코드를 이용해서 시스템의 Endian 을 체크할수 있다.

 

void main(void)

{

    int i = 0x00000001;

 

    if( ((char *)&i)[0] )

        printf( "Littile Endian\n" );

    else

        printf( "Big Endian\n" );

 

    /* ANOTHER */

if( *((char *)&i+0) )

        printf( "Littile Endian\n" );

    else

        printf( "Big Endian\n" );

}

/**
BUILD & MAKE(WINDOW & LINUX COMMON)
-------------------------------------------------------------------
CC = gcc

CFLAGS += -I -g -Wall -Wno-unused-variable
LIBS += -L. -lcurl -ljson-c

.c.o:
$(CC) -c $< $(CFLAGS)

all: build

common.o : common.c
pushcall.o : pushcall.c

pushcall: pushcall.o common.o
$(CC) -o $@ $^ $(LIBS)
BUILD_FILES += pushcall

build: $(BUILD_FILES)

clean:
rm -f *.o
rm -f $(BUILD_FILES)
-------------------------------------------------------------------
*/
#include 
#include 

#include <curl/curl.h>
#include 
#include 
#include 
#include <sys/time.h>
#include "json.h"

#define MAX_MSG_CNT 14
#define authorization_str "AUTHORIZATION:"
#define token_str "TOKEN:"

/* holder for curl fetch */
struct curl_fetch_st {
    char *payload;
    size_t size;
};

static json_object *google_pushcall(char *authorization, char *title, char *body, char *token);
static size_t curl_callback (void *contents, size_t size, size_t nmemb, void *userp);
static CURLcode curl_fetch_url(CURL *ch, const char *url, struct curl_fetch_st *fetch);
static int jsonparsing_result(const char *buf);
static int get_config_values(char *authorization, char *token);

int GetDate();
int GetTime();

int get_config_values(char *authorization, char *token)
{
FILE *fp=NULL;
char rbuf[1024];

if((fp=fopen("config.txt", "rt"))==NULL) return(-1);

while(1)
{
memset(rbuf,0x00,sizeof(rbuf));
if(fgets(rbuf, sizeof(rbuf), fp)==NULL) break;

rbuf[strlen(rbuf)-1]=0x00;

if(rbuf[0] == '#') continue;

if(strstr(rbuf, authorization_str) != NULL)
{
strcpy(authorization, strstr(rbuf, authorization_str) + strlen(authorization_str));
}
if(strstr(rbuf, token_str) != NULL)
{
strcpy(token, strstr(rbuf, token_str) + strlen(token_str));
}
}
if(fp != NULL) fclose(fp);
return(0);
}

int main(int argc, char *argv[])
{
json_object *json = NULL;
int rc;

char authorization[1024];
char token[300];

char *title = "FCM Message";
char body[4096];
char extendedmsg[MAX_MSG_CNT][300] = 
{
"Miracles happen to only those who believe in them.",
"Think like a man of action and act like man of thought.",
"Courage is very important. Like a muscle, it is strengthened by use.",
"Life is the art of drawing sufficient conclusions from insufficient premises.",
"By doubting we come at the truth.",
"A man that has no virtue in himself, ever envies virtue in others.",
"When money speaks, the truth keeps silent.",
"Better the last smile than the first laughter.",
"Painless poverty is better than embittered wealth.",
"A poet is the painter of the soul.",
"Error is the discipline through which we advance.",
"Faith without deeds is useless.",
"Weak things united become strong.",
"We give advice, but we cannot give conduct.",
};

    memset(authorization,0x00,sizeof(authorization));
memset(token,0x00,sizeof(token));

rc=get_config_values(authorization, token);
if(rc)
{
//ERROR
}
else
{
fprintf(stderr, "authorization:(%s)\n", authorization);
fprintf(stderr, "token:        (%s)\n", token);
}

    memset(body,0x00,sizeof(body));
sprintf(body, "Body>>(%d-%d)(%d)(%s)", GetDate(), GetTime(), GetTime() % MAX_MSG_CNT, extendedmsg[GetTime() % MAX_MSG_CNT]);

json = google_pushcall(authorization, title, body, token);
if(json == NULL) {
return(-1);
}

/* debugging */
    fprintf(stderr, "RECV>>Parsed JSON: %s\n", json_object_to_json_string(json));

rc = jsonparsing_result(json_object_to_json_string(json));
if(rc)
{
//error
}
else
{
//INSERT PUSH_SIT_EVENT_HIST
}

if(json != NULL) json_object_put(json);

return(0);
}

/* callback for curl fetch */
size_t curl_callback (void *contents, size_t size, size_t nmemb, void *userp) {
    size_t realsize = size * nmemb;                             /* calculate buffer size */
    struct curl_fetch_st *p = (struct curl_fetch_st *) userp;   /* cast pointer to fetch struct */

    /* expand buffer */
    p->payload = (char *) realloc(p->payload, p->size + realsize + 1);

    /* check buffer */
    if (p->payload == NULL) {
      /* this isn't good */
      fprintf(stderr, "ERROR: Failed to expand buffer in curl_callback\n");
      /* free buffer */
      free(p->payload);
      /* return */
      return -1;
    }

    /* copy contents to buffer */
    memcpy(&(p->payload[p->size]), contents, realsize);

    /* set new buffer size */
    p->size += realsize;

    /* ensure null termination */
    p->payload[p->size] = 0;

    /* return size */
    return realsize;
}

/* fetch and return url body via curl */
CURLcode curl_fetch_url(CURL *ch, const char *url, struct curl_fetch_st *fetch) {
    CURLcode rcode;                   /* curl result code */

    /* init payload */
    fetch->payload = (char *) calloc(1, sizeof(fetch->payload));

    /* check payload */
    if (fetch->payload == NULL) {
        /* log error */
        fprintf(stderr, "ERROR: Failed to allocate payload in curl_fetch_url\n");
        /* return error */
        return CURLE_FAILED_INIT;
    }

    /* init size */
    fetch->size = 0;

    /* set url to fetch */
    curl_easy_setopt(ch, CURLOPT_URL, url);
    /* set calback function */
    curl_easy_setopt(ch, CURLOPT_WRITEFUNCTION, curl_callback);
    /* pass fetch struct pointer */
    curl_easy_setopt(ch, CURLOPT_WRITEDATA, (void *) fetch);
    /* set default user agent */
    //curl_easy_setopt(ch, CURLOPT_USERAGENT, "libcurl-agent/1.0");
curl_easy_setopt(ch, CURLOPT_USERAGENT, "curl/7.65.1");
    /* set timeout */
    curl_easy_setopt(ch, CURLOPT_TIMEOUT, 30);
    /* enable location redirects */
    curl_easy_setopt(ch, CURLOPT_FOLLOWLOCATION, 1);
    /* set maximum allowed redirects */
    curl_easy_setopt(ch, CURLOPT_MAXREDIRS, 1);
    /* fetch the url */
    rcode = curl_easy_perform(ch);

    /* return */
    return rcode;
}

json_object *google_pushcall(char *authorization, char *title, char *body, char *token)
{
    CURL *ch;                                               /* curl handle */
    CURLcode rcode;                                         /* curl result code */

    json_object *json=NULL;                                 /* json post body */
json_object *jsonobj=NULL;                              /* json post body */

    enum json_tokener_error jerr = json_tokener_success;    /* json parse error */

    struct curl_fetch_st curl_fetch;                        /* curl fetch struct */
    struct curl_fetch_st *cf = &curl_fetch;                 /* pointer to fetch struct */
    struct curl_slist *headers = NULL;                      /* http headers to send with request */

char post_data  [4096] = {0x00,};

char header_definition[2048];

char *url = "https://fcm.googleapis.com/fcm/send";

    /* init curl handle */
    if ((ch = curl_easy_init()) == NULL) {
        /* log error */
        fprintf(stderr, "ERROR: Failed to create curl handle in fetch_session\n");
        /* return error */
        return NULL;
    }

    /* set content type */
memset(header_definition,0x00,sizeof(header_definition));
sprintf(header_definition, "Authorization: key=%s", authorization);
    headers = curl_slist_append(headers, header_definition);
    headers = curl_slist_append(headers, "Content-Type: application/json");

    /* create json object for post */
    json      = json_object_new_object();
jsonobj   = json_object_new_object();

    /* build post data */
    /*-----------------------------------------------------------------------------------
json_object_object_add(jsoninobj, "title"       , json_object_new_string(title));
    json_object_object_add(jsoninobj, "body"        , json_object_new_string(body));
    json_object_object_add(jsonobj  , "notification", jsoninobj);
json_object_object_add(jsonobj  , "token"       , json_object_new_string(token));
json_object_object_add(json     , "message"     , jsonobj);
-----------------------------------------------------------------------------------*/
json_object_object_add(json  ,  "to"          , json_object_new_string(token));
json_object_object_add(jsonobj, "title"       , json_object_new_string(title));
    json_object_object_add(jsonobj, "body"        , json_object_new_string(body));
    json_object_object_add(json  ,  "notification", jsonobj);

memset(post_data, 0x00, sizeof(post_data));
sprintf(post_data, "%s", json_object_to_json_string(json));

#if(1)
/* debugging */
    fprintf(stderr, "SEND>>Parsed JSON: [%s]\n", post_data);
#endif

    /* set curl options */
    curl_easy_setopt(ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_easy_setopt(ch, CURLOPT_HTTPHEADER, headers);
    curl_easy_setopt(ch, CURLOPT_POSTFIELDS, post_data);
curl_easy_setopt(ch, CURLOPT_VERBOSE, 1L);
curl_easy_setopt(ch, CURLOPT_POST, 1L);
/* disconnect if we can't validate server's cert */ 
    curl_easy_setopt(ch, CURLOPT_SSL_VERIFYPEER, 0L);
curl_easy_setopt(ch, CURLOPT_SSL_VERIFYHOST, 0L);

    /* fetch page and capture return code */
    rcode = curl_fetch_url(ch, url, cf);

    //FREE
    curl_easy_cleanup(ch);
    curl_slist_free_all(headers);

    if(json != NULL) json_object_put(json);
if(jsonobj != NULL) json_object_put(jsonobj);

    /* check return code */
    if (rcode != CURLE_OK || cf->size < 1) {
        /* log error */
        fprintf(stderr, "ERROR: Failed to fetch url (%s) - curl said: %s\n",
            url, curl_easy_strerror(rcode));
        /* return error */
        return NULL;
    }

    /* check payload */
    if (cf->payload != NULL) {

#if(0)
        /* print result */
        fprintf(stderr, "CURL Returned: [%s]\n", cf->payload);
#endif

        /* parse return */
        json = json_tokener_parse_verbose(cf->payload, &jerr);
        /* free payload */
        free(cf->payload);
    } else {
        /* error */
        fprintf(stderr, "ERROR: Failed to populate payload\n");
        /* free payload */
        free(cf->payload);
        /* return */
        return NULL;
    }

    /* check error */
    if (jerr != json_tokener_success) {
        /* error */
        fprintf(stderr, "ERROR: Failed to parse json string\n");
        /* free json object */
        if(json != NULL) json_object_put(json);
        /* return */
        return NULL;
    }
return json;
}

int jsonparsing_result(const char *buf)
{
int ii, rc;
char keystr[100],successtmp[100];
struct json_object *jsonjob   = NULL;
struct json_object *jsonvalue = NULL;

jsonjob = json_tokener_parse(buf);
if(NULL == jsonjob) {
return -1;
}
printf("\n\n\n\n");

    memset(keystr, 0x00, sizeof(keystr));
strcpy(keystr, "success");
json_object_object_get_ex(jsonjob, keystr, &jsonvalue);
memset(successtmp, 0x00, sizeof(successtmp));
strcpy(successtmp, json_object_get_string(jsonvalue));

if(atoi(successtmp) == 1 || atoi(successtmp) == 0)
{
if(atoi(successtmp) == 0) printf("[FAIL]BASIC DATA-----------------------------------\n");
if(atoi(successtmp) == 1) printf("[SUCC]BASIC DATA-----------------------------------\n");

memset(keystr, 0x00, sizeof(keystr));
strcpy(keystr, "multicast_id");
json_object_object_get_ex(jsonjob, keystr, &jsonvalue);
printf("[%s][%s]\n", keystr, json_object_get_string(jsonvalue));

memset(keystr, 0x00, sizeof(keystr));
strcpy(keystr, "success");
json_object_object_get_ex(jsonjob, keystr, &jsonvalue);
printf("[%s][%s]\n", keystr, json_object_get_string(jsonvalue));

memset(keystr, 0x00, sizeof(keystr));
strcpy(keystr, "failure");
json_object_object_get_ex(jsonjob, keystr, &jsonvalue);
printf("[%s][%s]\n", keystr, json_object_get_string(jsonvalue));

memset(keystr, 0x00, sizeof(keystr));
strcpy(keystr, "canonical_ids");
json_object_object_get_ex(jsonjob, keystr, &jsonvalue);
printf("[%s][%s]\n", keystr, json_object_get_string(jsonvalue));

struct json_object *pdata = NULL;
if(json_object_object_get_ex(jsonjob, "results", &pdata)) 
{
for (ii = 0; ii < json_object_array_length(pdata); ii++) 
{
if(ii==0)
{
printf("ARRAY DATA[%.4d]-----------------------------------\n", json_object_array_length(pdata));
}

struct json_object *successtmp = json_object_array_get_idx(pdata, ii);

memset(keystr, 0x00, sizeof(keystr));
strcpy(keystr, "message_id");
rc = json_object_object_get_ex(successtmp, keystr, &jsonvalue);
if(rc)
{
printf("rc:[%d]", rc);
printf(",index[%.3d],key[%s]:[%s]\n", ii + 1, keystr, json_object_get_string(jsonvalue));
}

memset(keystr, 0x00, sizeof(keystr));
strcpy(keystr, "error");
rc = json_object_object_get_ex(successtmp, keystr, &jsonvalue);
if(rc)
{
printf("rc:[%d]", rc);
printf(",index[%.3d],key[%s]:[%s]\n", ii + 1, keystr, json_object_get_string(jsonvalue));
}
}
}
}
else
{
return(-2);
}

return(0);
}

/*NEEDED FILES------------------------------------------------------------------------
bash-3.1$ ls -lrt *.c
-rw-r--r-- 1 kiwoom Administrators  7660 Jul 12 10:31 common.c
-rw-r--r-- 1 kiwoom Administrators 12584 Jul 25 10:19 pushcall.c
bash-3.1$ ls -lrt *.h
-rw-r--r-- 1 kiwoom Administrators  1064 Jul  8 08:51 vasprintf_compat.h
-rw-r--r-- 1 kiwoom Administrators   276 Jul  8 08:51 strerror_override_private.h
-rw-r--r-- 1 kiwoom Administrators   510 Jul  8 08:51 strerror_override.h
-rw-r--r-- 1 kiwoom Administrators   367 Jul  8 08:51 strdup_compat.h
-rw-r--r-- 1 kiwoom Administrators   943 Jul  8 08:51 snprintf_compat.h
-rw-r--r-- 1 kiwoom Administrators   506 Jul  8 08:51 random_seed.h
-rw-r--r-- 1 kiwoom Administrators  3858 Jul  8 08:51 printbuf.h
-rw-r--r-- 1 kiwoom Administrators   644 Jul  8 08:51 math_compat.h
-rw-r--r-- 1 kiwoom Administrators 10219 Jul  8 08:51 linkhash.h
-rw-r--r-- 1 kiwoom Administrators  3181 Jul  8 08:51 json_visit.h
-rw-r--r-- 1 kiwoom Administrators  2985 Jul  8 08:51 json_util.h
-rw-r--r-- 1 kiwoom Administrators  7150 Jul  8 08:51 json_tokener.h
-rw-r--r-- 1 kiwoom Administrators  4832 Jul  8 08:51 json_pointer.h
-rw-r--r-- 1 kiwoom Administrators  1499 Jul  8 08:51 json_object_private.h
-rw-r--r-- 1 kiwoom Administrators  8274 Jul  8 08:51 json_object_iterator.h
-rw-r--r-- 1 kiwoom Administrators 38349 Jul  8 08:51 json_object.h
-rw-r--r-- 1 kiwoom Administrators   350 Jul  8 08:51 json_inttypes.h
-rw-r--r-- 1 kiwoom Administrators   143 Jul  8 08:51 json_config.h
-rw-r--r-- 1 kiwoom Administrators  1185 Jul  8 08:51 json_c_version.h
-rw-r--r-- 1 kiwoom Administrators   810 Jul  8 08:51 json.h
-rw-r--r-- 1 kiwoom Administrators  1724 Jul  8 08:51 debug.h
-rw-r--r-- 1 kiwoom Administrators  5761 Jul  8 08:51 config.h
-rw-r--r-- 1 kiwoom Administrators  1554 Jul  8 08:51 arraylist.h
bash-3.1$ ls -lrt *.a
-rw-r--r-- 1 kiwoom Administrators 81888 Jul  8 08:51 libjson-c.a
-rw-r--r-- 1 kiwoom Administrators 51808 Jul  8 08:51 libcurl.dll.a
bash-3.1$ ls -lrt *.dll
-rwxr-xr-x 1 kiwoom Administrators  528896 Jul  8 08:51 libssl-1_1.dll
-rwxr-xr-x 1 kiwoom Administrators  985720 Jul  8 08:51 libcurl.dll
-rwxr-xr-x 1 kiwoom Administrators 2499072 Jul  8 08:51 libcrypto-1_1.dll
-rwxr-xr-x 1 kiwoom Administrators  505344 Jul  8 08:51 brotlienc.dll
-rwxr-xr-x 1 kiwoom Administrators   44032 Jul  8 08:51 brotlidec.dll
-rwxr-xr-x 1 kiwoom Administrators  132096 Jul  8 08:51 brotlicommon.dll
bash-3.1$
-----------------------------------------------------------------------------------*/

/**
 * example C code using libcurl and json-c
 * to post and return a payload using
 * http://jsonplaceholder.typicode.com
 *
 * Requirements:
 *
 * json-c - https://github.com/json-c/json-c
 * libcurl - http://curl.haxx.se/libcurl/c
 *
 * Build:
 *
 * gcc test.c -lcrypto -lcurl -ljson-c -o test

 *

 * DESCRIPTION

   - 특정사이트에 접속해서 데이타를 불러오는역할은 curl lib가 담당한다.

   - 데이타 입력및 출력의 인터페이스에 필요한 데이타의 암호화는 ​lcrypto lib가 담당한다.

   - 출력데이타를 복호화 했을때에, JSON형식의 데이타를 파싱하는데에는 ​ljson-c lib가 필요하다.
 * 
 */

/* standard includes */
#include <stdio.h>
#include <string.h>
#include <netdb.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#include <curl/curl.h>
#include <iconv.h>
#include <locale.h>
#include <langinfo.h>
#include <openssl/aes.h>
#include <time.h>
#include <sys/time.h>
#include <json-c/json.h>

#define MAX_AES_BUFF_SIZE 2048
#define MAX_FSS_STRING_SIZE 100

 

int __debug;


const unsigned char fw_aes_key[16+1] = {0X45, 0X72, 0X23, 0X33, 0X77, 0XAB, 0X6C, 0X6C, 0XFD, 0X59, 0X6C, 0X75, 0X74, 0X69, 0X6F, 0X6E, 0x00};

 

/* holder for curl fetch */
struct curl_fetch_st {
    char *payload;
    size_t size;
};

 

/*

 * Function prototype

 */
json_object *sbo634_wascall(char *MSGCODE, char *ACCNO, char *PAGE);
size_t curl_callback (void *contents, size_t size, size_t nmemb, void *userp);
CURLcode curl_fetch_url(CURL *ch, const char *url, struct curl_fetch_st *fetch);

static void e_hex_convert(const void* pv, size_t len, char *outBuff) {
    const unsigned char * p = (const unsigned char*)pv;
 
    if (NULL == pv) {
        return;
    }
    else

    {
        size_t i = 0;
        int hexLen = 0;
        char editb[8];


        memset (editb, 0x00, sizeof(editb));
        for (; i<len;++i) {
            sprintf(editb, "%02X", *p++);
            memcpy(outBuff+hexLen, editb, 2);
            hexLen += 2; 
        }
    }
    return;
}

static void d_hex_convert(unsigned char *pv, size_t len, char *outBuff) {
    const unsigned char * p = (const unsigned char*)pv;
 
    int ii, kk, jj;
 
    kk=0;
    ii=0;
    while(1)
    {
        if(ii >= len) break;
  
        jj=0;
        if(pv[ii] == 'F') pv[ii] = 15;
        else if(pv[ii] == 'E') pv[ii] = 14;
        else if(pv[ii] == 'D') pv[ii] = 13;
        else if(pv[ii] == 'C') pv[ii] = 12;
        else if(pv[ii] == 'B') pv[ii] = 11;
        else if(pv[ii] == 'A') pv[ii] = 10;
        else if(pv[ii] == '9') pv[ii] = 9;
        else if(pv[ii] == '8') pv[ii] = 8;
        else if(pv[ii] == '7') pv[ii] = 7;
        else if(pv[ii] == '6') pv[ii] = 6;
        else if(pv[ii] == '5') pv[ii] = 5;
        else if(pv[ii] == '4') pv[ii] = 4;
        else if(pv[ii] == '3') pv[ii] = 3;
        else if(pv[ii] == '2') pv[ii] = 2;
        else if(pv[ii] == '1') pv[ii] = 1;
        else if(pv[ii] == '0') pv[ii] = 0;
  
        if((pv[ii] & 0x08) > 0) jj = jj + 128;
        if((pv[ii] & 0x04) > 0) jj = jj + 64;
        if((pv[ii] & 0x02) > 0) jj = jj + 32;
        if((pv[ii] & 0x01) > 0) jj = jj + 16;
  
        if(pv[ii+1] == 'F') pv[ii+1] = 15;
        else if(pv[ii+1] == 'E') pv[ii+1] = 14;
        else if(pv[ii+1] == 'D') pv[ii+1] = 13;
        else if(pv[ii+1] == 'C') pv[ii+1] = 12;
        else if(pv[ii+1] == 'B') pv[ii+1] = 11;
        else if(pv[ii+1] == 'A') pv[ii+1] = 10;
        else if(pv[ii+1] == '9') pv[ii+1] = 9;
        else if(pv[ii+1] == '8') pv[ii+1] = 8;
        else if(pv[ii+1] == '7') pv[ii+1] = 7;
        else if(pv[ii+1] == '6') pv[ii+1] = 6;
        else if(pv[ii+1] == '5') pv[ii+1] = 5;
        else if(pv[ii+1] == '4') pv[ii+1] = 4;
        else if(pv[ii+1] == '3') pv[ii+1] = 3;
        else if(pv[ii+1] == '2') pv[ii+1] = 2;
        else if(pv[ii+1] == '1') pv[ii+1] = 1;
        else if(pv[ii+1] == '0') pv[ii+1] = 0;
  
        if((pv[ii+1] & 0x08) > 0) jj = jj + 8;
        if((pv[ii+1] & 0x04) > 0) jj = jj + 4;
        if((pv[ii+1] & 0x02) > 0) jj = jj + 2;
        if((pv[ii+1] & 0x01) > 0) jj = jj + 1;
  
        outBuff[kk] = jj;
  
        kk = kk + 1;
        ii = ii + 2;
    }
    return;
}

static int e_makeAesPacket(unsigned char *EncryptText, int EncryptTextLen, unsigned char *DecryptText) {
 
    AES_KEY enc_key;
    long idx=0;
    unsigned char padBuff[MAX_AES_BUFF_SIZE];
    unsigned char encBuff[MAX_AES_BUFF_SIZE];
    int ii;

    size_t encPadLen = ((EncryptTextLen + AES_BLOCK_SIZE) / AES_BLOCK_SIZE) * AES_BLOCK_SIZE;

    memset(padBuff, 0x00, MAX_AES_BUFF_SIZE);
    memset(encBuff, 0x00, MAX_AES_BUFF_SIZE);
 
    AES_set_encrypt_key(fw_aes_key, 128, &enc_key);

    memcpy(padBuff, EncryptText, EncryptTextLen);
    for (ii = EncryptTextLen; ii < encPadLen; ii++) {
        padBuff[ii] = (encPadLen - EncryptTextLen);
    }

    while(idx < encPadLen) {
        AES_ecb_encrypt(padBuff+idx, encBuff+idx, &enc_key, AES_ENCRYPT);
        idx += AES_BLOCK_SIZE;
    }
 
    printf("e_makeAesPacket[%d]", strlen(encBuff));

    e_hex_convert(encBuff, encPadLen, DecryptText);

    return(strlen(DecryptText));
}

static int d_makeAesPacket(unsigned char *DecryptText, int DecryptTextLen, unsigned char *PlainText) {
 
    AES_KEY dec_key;
    long idx=0;
    unsigned char outBuff[MAX_AES_BUFF_SIZE];
    int ii, kk, jj;

    memset(outBuff, 0x00, MAX_AES_BUFF_SIZE);
 
    AES_set_decrypt_key(fw_aes_key, 128, &dec_key);
 
    size_t encPadLen = strlen(DecryptText) / 2;
    d_hex_convert(DecryptText, DecryptTextLen, outBuff);
 
    printf("d_makeAesPacket[%d]", strlen(outBuff));

    while(idx < encPadLen) {
        AES_ecb_encrypt(outBuff+idx, PlainText+idx, &dec_key, AES_DECRYPT);
        idx += AES_BLOCK_SIZE;
    }
    if(__debug) printf(">>%s\n", PlainText);

    jj=PlainText[encPadLen-1];
    ii=0;
    for(kk=encPadLen-2; kk>0; kk--)
    {
        if(PlainText[kk] == jj)
        {
            PlainText[kk]=0x00;
        }
        else break;
    }
    return(strlen(PlainText));
}

/* callback for curl fetch */
size_t curl_callback (void *contents, size_t size, size_t nmemb, void *userp) {
    size_t realsize = size * nmemb;                             /* calculate buffer size */
    struct curl_fetch_st *p = (struct curl_fetch_st *) userp;   /* cast pointer to fetch struct */

    /* expand buffer */
    p->payload = (char *) realloc(p->payload, p->size + realsize + 1);

    /* check buffer */
    if (p->payload == NULL) {
      /* this isn't good */
      fprintf(stderr, "ERROR: Failed to expand buffer in curl_callback");
      /* free buffer */
      free(p->payload);
      /* return */
      return -1;
    }

    /* copy contents to buffer */
    memcpy(&(p->payload[p->size]), contents, realsize);

    /* set new buffer size */
    p->size += realsize;

    /* ensure null termination */
    p->payload[p->size] = 0;

    /* return size */
    return realsize;
}

/* fetch and return url body via curl */
CURLcode curl_fetch_url(CURL *ch, const char *url, struct curl_fetch_st *fetch) {
    CURLcode rcode;                   /* curl result code */

    /* init payload */
    fetch->payload = (char *) calloc(1, sizeof(fetch->payload));

    /* check payload */
    if (fetch->payload == NULL) {
        /* log error */
        fprintf(stderr, "ERROR: Failed to allocate payload in curl_fetch_url");
        /* return error */
        return CURLE_FAILED_INIT;
    }

    /* init size */
    fetch->size = 0;

    /* set url to fetch */
    curl_easy_setopt(ch, CURLOPT_URL, url);

    /* set calback function */
    curl_easy_setopt(ch, CURLOPT_WRITEFUNCTION, curl_callback);

    /* pass fetch struct pointer */
    curl_easy_setopt(ch, CURLOPT_WRITEDATA, (void *) fetch);

    /* set default user agent */
    curl_easy_setopt(ch, CURLOPT_USERAGENT, "libcurl-agent/1.0");

    /* set timeout */
    curl_easy_setopt(ch, CURLOPT_TIMEOUT, 30);

    /* enable location redirects */
    curl_easy_setopt(ch, CURLOPT_FOLLOWLOCATION, 1);

    /* set maximum allowed redirects */
    curl_easy_setopt(ch, CURLOPT_MAXREDIRS, 1);

    /* fetch the url */
    rcode = curl_easy_perform(ch);

    /* return */
    return rcode;
}

json_object *sbo634_wascall(char *MSGCODE, char *ACCNO, char *PAGE)
{
    CURL *ch;                                               /* curl handle */
    CURLcode rcode;                                         /* curl result code */

    json_object *json;                                      /* json post body */
    enum json_tokener_error jerr = json_tokener_success;    /* json parse error */

    struct curl_fetch_st curl_fetch;                        /* curl fetch struct */
    struct curl_fetch_st *cf = &curl_fetch;                 /* pointer to fetch struct */
    struct curl_slist *headers = NULL;                      /* http headers to send with request */
 
    char post_data  [1024*32] = {0x00,};
    unsigned char TextPlain  [1204L * 128L] = {0x00,};
 
    unsigned char inBuff[MAX_AES_BUFF_SIZE];
    unsigned char txParam[MAX_AES_BUFF_SIZE];
    unsigned char txRemark[MAX_AES_BUFF_SIZE];
 
    int rlen;

    /* url to test site */
    char *url = "http://cyper-01:44444/GW/rest/service.do";
    printf("[URL]%s\n", url);

    /* init curl handle */
    if ((ch = curl_easy_init()) == NULL) {
        /* log error */
        fprintf(stderr, "ERROR: Failed to create curl handle in fetch_session");
        /* return error */
        return NULL;
    }

    /* set content type */
    //headers = curl_slist_append(headers, "Accept: application/json");
    //headers = curl_slist_append(headers, "Content-Type: application/json");

    /* create json object for post */
    json = json_object_new_object();

    /* build post data */
    json_object_object_add(json, "MSGCODE", json_object_new_string(MSGCODE)); 
    json_object_object_add(json, "ACCNO", json_object_new_string(ACCNO)); 
    json_object_object_add(json, "PAGE", json_object_new_string(PAGE)); 
 
    memset(inBuff, 0x00, sizeof(inBuff));
    sprintf(inBuff, "%s", json_object_to_json_string(json));
    printf(">>BEFORE ENCRYPT:::msg=%s\n", json_object_to_json_string(json));
    rlen = e_makeAesPacket(inBuff, strlen(inBuff), txRemark);
    if (rlen < 0) {
        printf("AesPacket make failed(%s)", inBuff);
        return NULL;
    }
    sprintf(post_data, "msg=%s", txRemark);
    printf(">>AFTER ENCRYPT:::%s", post_data);
    printf("\n\n\n\n");
 

    /* set curl options */
    curl_easy_setopt(ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_easy_setopt(ch, CURLOPT_HTTPHEADER, headers);
    curl_easy_setopt(ch, CURLOPT_POSTFIELDS, post_data);
    curl_easy_setopt(ch, CURLOPT_VERBOSE, 1L);
    curl_easy_setopt(ch, CURLOPT_POST, 1L);

    /* fetch page and capture return code */
    rcode = curl_fetch_url(ch, url, cf);

    //FREE
    curl_easy_cleanup(ch);
    curl_slist_free_all(headers);
    json_object_put(json);

    /* check return code */
    if (rcode != CURLE_OK || cf->size < 1) {
        /* log error */
        fprintf(stderr, "ERROR: Failed to fetch url (%s) - curl said: %s",
            url, curl_easy_strerror(rcode));
        /* return error */
        return NULL;
    }

    /* check payload */
    if (cf->payload != NULL)

​    {
        /* print result */
        printf("CURL Returned: \n%s\n", cf->payload);
  
        rlen = d_makeAesPacket((unsigned char *)cf->payload, strlen(cf->payload), TextPlain);
        if (rlen < 0) {
            printf("d_makeAesPacket make failed(%s)", inBuff);
            return NULL;
        }
 
        /* parse return */
        json = json_tokener_parse_verbose(TextPlain, &jerr);
        /* free payload */
        free(cf->payload);
     }

     else

     {
        /* error */
        fprintf(stderr, "ERROR: Failed to populate payload");
        /* free payload */
        free(cf->payload);
        /* return */
        return NULL;
    }

    /* check error */
    if (jerr != json_tokener_success) {
        /* error */
        fprintf(stderr, "ERROR: Failed to parse json string");
        /* free json object */
        json_object_put(json);
        /* return */
        return NULL;
    }
    return json;
}

 

char CreditBalanceDefineName[44][100] = {"MSGCODE",
"RESULT","REASON","ACCNO","AO","LIMIT","CREDIT-AVAI","ASSETS","LIABILITIES",
"EQUITY","CASHBAL","LMV","COLLATERAL","DEBT","SMV","MR","BUYMR",
"SELLMR","EE","PP","CALLMARGIN","SHORTCALL","CALLFORCESELL","CALL_LMV","CALL_SMV",
"FORCE_LMV","FORCE_SMV","MARGINRATIO","WITHDRAWAL","ACTION","ACCEE","BUYCR50",
"BUYCR60","BUYCR70","MTMEE","MTMBUYCR50","MTMBUYCR60","MTMBUYCR70","MTMMRATIO",
"MTMCALLM35","TOTALBUY","TOTALSELL","PAGE","NEXTPAGE"};

 

 

char CreditPortDefineName[9][100] = {"MSGCODE",
"RESULT","REASON","ACCNO","TAMOUNT","TMKTVALUE","PAGE",
"NEXTPAGE","COUNT"};

 

int main(int argc, char *argv[])
{
    json_object *json = NULL;
    json_object *array = NULL;
    json_object *pdata = NULL;
    json_object *jvalue = NULL;
 
    char MSGCODE[MAX_FSS_STRING_SIZE];
    char ACCNO[MAX_FSS_STRING_SIZE];
    char PAGE[MAX_FSS_STRING_SIZE];
 
    int kk;
 
    if(argc < 2)
    {
        printf("[1]:MSGCODE>ACR, ACCNO>, PAGE>1 + DEBUG(D)\n");
        printf("[2]:MSGCODE>ACP, ACCNO>, PAGE>1 + DEBUG(D)\n");
        return(-1);
    }

    if(argc == 3)
    {
        if(argv[2][0] == 'D') __debug = 1;
        else __debug = 0;
    }
 
    memset(MSGCODE,0x00,sizeof(MSGCODE));
    memset(ACCNO,0x00,sizeof(ACCNO));
    memset(PAGE,0x00,sizeof(PAGE));
 
    if(argv[1][0] =='1')
    {
       strcpy(MSGCODE, "ACR");
       strcpy(ACCNO, "987654321");
       strcpy(PAGE, "1");  
    }
    else if(argv[1][0] =='2')
    {
       strcpy(MSGCODE, "ACP");
       strcpy(ACCNO, "987654321");
       strcpy(PAGE, "1");  
    }
    else
    {
       printf("Argument IS 1 or 2 !!!!!!!\n");
       return(-1);
    }
 
    json = sbo634_wascall(MSGCODE, ACCNO, PAGE);
    if(json == NULL) {
       return(-1);
    }
 
    /* debugging */
    printf("Parsed JSON: %s\n", json_object_to_json_string(json));
 
    char *creditvalue = NULL;
 
    printf("\n\n\n\n\n>>>>>>>>\n");

    if(argv[1][0]=='2')
    for(kk=0; kk<9; kk++)
    {
         if (json_object_object_get_ex(json, CreditPortDefineName[kk], &pdata)) {
         creditvalue = (char *)json_object_get_string(pdata);
         printf("[%.3d]%20s:[%s]\n", kk+1, CreditPortDefineName[kk], creditvalue);
         }
    }
  
    if(argv[1][0]=='1')
    for(kk=0; kk<44; kk++)
    {
         if (json_object_object_get_ex(json, CreditBalanceDefineName[kk], &pdata)) {
         creditvalue = (char *)json_object_get_string(pdata);
         printf("[%.3d]%20s:[%s]\n", kk+1, CreditBalanceDefineName[kk], creditvalue);
         }
    }
 
    json_object_put(json);
 
    return(0);

}

 

/*----복호화한 출력 JSON포맷 ----------------------------------------------------------------------------------------------

{ "PP": "3890427.94", "BUYMR": "0.00", "COLLATERAL": "0.00", "MTMEE": "1945213.97", "BUYCR70": "2778877.10", "CASHBAL": "1945213.97", "SHORTCALL": "1945213.97", "CREDIT-AVAI": "3890427.94", "TOTALB": "0.00", "LIMIT": "12000000.00", "LIABILITIES": "0.00", "DEBT": "0.00", "MARGINRATIO": "1.0000", "SHORTFORCE": "1945213.97", "MTMCALLM35": "0.35", "ACCNO": "0058866", "MTMBUYCR50": "3890427.94", "MTMBUYCR70": "2778877.10", "REASON": "complete", "BUYCR50": "3890427.94", "EQUITY": "1945213.97", "ASSETS": "1945213.97", "EE": "1945213.97", "BUYCR60": "3242023.28", "MSGCODE": "RCR", "MR": "0.00", "SELLMR": "0.00", "CALLMARGIN": "0.00", "CALLFORCESELL": "0.00", "AO": "9233", "ACCEE": "1945213.97", "LMV": "0.00", "CALL_SMV": "40.00", "ACTION": "", "FORCE_SMV": "30.00", "TOTALS": "0.00", "MTMBUYCR60": "3242023.28", "CALL_LMV": "35.00", "MTMMRATIO": "0.00", "SMV": "0.00", "WITHDRAWAL": "1945213.97", "RESULT": "0", "FORCE_LMV": "25.00" }

-----------------------------------------------------------------------------------------------------------------------*/

/*----복호화한 출력 JSON포맷 ----------------------------------------------------------------------------------------------

{ "STOCKLISTS": [ ], "ACCNO": "0058866", "MSGCODE": "RCP", "TAMOUNT": "0.00", "PAGE": "1", "COUNT": "0", "NEXTPAGE": "0", "TMKTVALUE": "0.00", "REASON": "complete", "RESULT": "0" }

-----------------------------------------------------------------------------------------------------------------------*/


 

/**
 @file
 @copyright COPYRIGHT ⓒ2017 SUKSU COMPUTER. ALL RIGHTS RESERVED. <br/>
 @note
 @author
 @section history Major History

 

* 어떤 JSON데이타를 자동으로 파싱하려고 하면, 굉장히 복잡하다. 우리는 REQUEST와 RESPONSE에 서로 규약되어 있는

데이타의 포맷에 맞춰서 JSON함수를 이용해, 데이타를 파싱하면 된다.

이는 소켓통신에서, 데이타의 규약과 마찬가지라고 보면 될것이다. 즉 RESPONSE JSON데이타의 포맷과 형식을 미리알고 있어야한다.
​     


​      */

 

 

#include <json-c/json.h>    //REDHAT LINUX계열
#include <stdio.h>
#include <string.h>

 

//컴파일방법

//gcc json2.c -ljson-c -o json2

 

char buf[1204L * 128L];

 

int main(int argc, char *argv[]) 
{
     FILE *fp = fopen(argv[1], "r");
 
     if(argc != 2)
     {
        printf("gcc json2.c -lcrypto -lcurl -ljson-c -o json2\n");
        return(-1);
     }
 
     if(NULL == fp)
     {
        fprintf(stderr, "fopen() failed");
        return -1;
     }

     int n = fread(buf, 1, sizeof(buf), fp);
     buf[n] = 0;

     struct json_object *jobj = NULL;

     jobj = json_tokener_parse(buf);    // ALREADY FORMATTING, SO, USE ONLY
     if(NULL == jobj) {
        return -1;
     }
 
     char KEY[100], SUBKEY[100];

     memset(KEY, 0x00, sizeof(KEY));
     strcpy(KEY, "result");
     printf("[%s][%s]\n", KEY, json_object_get_string(json_object_object_get(jobj, KEY)) );
 
     memset(KEY, 0x00, sizeof(KEY));
     strcpy(KEY, "reason");
     printf("[%s][%s]\n", KEY, json_object_get_string(json_object_object_get(jobj, KEY)) );
 
     struct json_object *pdata = NULL;
     if(json_object_object_get_ex(jobj, "summary", &pdata)) 
     {
        memset(KEY, 0x00, sizeof(KEY));
        strcpy(KEY, "totalpaid");
        printf("[%s][%s]\n", KEY, json_object_get_string(json_object_object_get(pdata, KEY)) );
  
        memset(KEY, 0x00, sizeof(KEY));
        strcpy(KEY, "totalreceived");
        printf("[%s][%s]\n", KEY, json_object_get_string(json_object_object_get(pdata, KEY)) );
  
        memset(KEY, 0x00, sizeof(KEY));
        strcpy(KEY, "totalunpaid");
        printf("[%s][%s]\n", KEY, json_object_get_string(json_object_object_get(pdata, KEY)) );
  
        memset(KEY, 0x00, sizeof(KEY));
        strcpy(KEY, "totalunreceived");
        printf("[%s][%s]\n", KEY, json_object_get_string(json_object_object_get(pdata, KEY)) );
    } 

    //struct json_object *pdata = NULL;
    if(json_object_object_get_ex(jobj, "data", &pdata)) 
    {
        int i;
        //int  json_object_array_length (struct json_object *obj) 
        for (i = 0; i < json_object_array_length(pdata); i++) 
        {
            //struct json_object *  json_object_array_get_idx (struct json_object *obj, int idx) 
            struct json_object *tmp = json_object_array_get_idx(pdata, i);
  
            printf("-----------------------------------\n");
            /*
            {"tradedate":"20170124",
             "settledate":"20170124",
             "cdrefer":"CN-20170124-01027",
             "amount":264554.830000,
             "status":"Received"
            },
            */
            memset(KEY, 0x00, sizeof(KEY));
            strcpy(KEY, "tradedate");
            printf("[%s][%s]", KEY, json_object_get_string(json_object_object_get(tmp, KEY)) );

            memset(KEY, 0x00, sizeof(KEY));
            strcpy(KEY, "settledate");
            printf("[%s][%s]", KEY, json_object_get_string(json_object_object_get(tmp, KEY)) );

            memset(KEY, 0x00, sizeof(KEY));
            strcpy(KEY, "cdrefer");
            printf("[%s][%s]", KEY, json_object_get_string(json_object_object_get(tmp, KEY)) );

            memset(KEY, 0x00, sizeof(KEY));
            strcpy(KEY, "amount");
            printf("[%s][%s]", KEY, json_object_get_string(json_object_object_get(tmp, KEY)) );

            memset(KEY, 0x00, sizeof(KEY));
            strcpy(KEY, "status");
            printf("[%s][%s]", KEY, json_object_get_string(json_object_object_get(tmp, KEY)) );

            printf("\n");
       }
   }
   return 0;
}

 

 

 

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

#include <time.h>

#include <fcntl.h>

#include <errno.h>

 

#define MAX_CNT 10

#define MAXTIX (24*60)

 

int l_xupdate(int xfds, char *a1, char *a2);

 

struct xxxidx 

{

int  recs; // record size

int recn[MAXTIX]; // Starting Record of HHMM

};

 

struct biglotTrade 

{

char    symbol[20];                

char    orderbookid[12];      

long biglotOrderQty; //VOLUME

int     biglotSequence;

long    biglotTotalVolumeTraded; //TOTAL VOLUME

double  biglotTurnover; //AMT

int     typeOfTrade;    //CASE 1 NEW, CASE 2 CANCEL(MUST)

double  doubleprice;

double  totalTurnoverTradeReport; //TOTAL AMT

char    tradeId[30];

char    dealId[30];

};

 

char DNS_PACKET[55][2][100] = {

{"TN-1-1508147706984-2","DN-1-1508147706984-1"},

{"TN-1-1508147696497-2","DN-1-1508147696497-1"},

{"TN-1-1508147685915-2","DN-1-1508147685915-1"},

{"TN-1-1508147668355-2","DN-1-1508147668355-1"},

{"TN-1-1508147651212-2","DN-1-1508147651212-1"},

{"TN-1-1508147637492-2","DN-1-1508147637492-1"},

{"TN-1-1508147635403-2","DN-1-1508147635403-1"},

{"TN-1-1508147624602-3","DN-1-1508147624602-2"},

{"TN-1-1508147579369-3","DN-1-1508147579369-2"},

{"TN-1-1508147553972-2","DN-1-1508147553972-1"}};

 

int main(int argc, char *argv[])

{

struct biglotTrade biglottrade[500];

int  xxfd;

char xfile[32];

int  ii, jj, cnt, rc;

 

sprintf(xfile, "%.20s", "BIGLOT");

xxfd = l_xopen(SAMFILE_PATH, xfile, O_RDWR);  //FOR UPDATE, RDWR NEEDED!!

if (xxfd < 0)

{

printf("Can't open BIGLOT file [%s][%s]. errno(%d)\n", DAT_JC_PATH, xfile, errno);

return(-1)

}

 

for (jj = 0; jj < MAX_CNT; jj++)

{

rc = l_xupdate(xxfd, DNS_PACKET[jj][0], DNS_PACKET[jj][1]);

if(rc)

{

printf("l_xupdate fail!!\n");

return(-1);

}

}

 

close(xxfd);

return 0;

}

 

int l_xupdate(int xfds, char *a1, char *a2)

{

struct  xxxidx  xxxidx;

struct  biglotTrade *tmpdjd;

int  rlen, wlen;

int  xsiz;

int maxr;

int  ii, cnt;

 

long xoff;

char buff[1024 * 100];

 

lseek(xfds, 0L, SEEK_SET);

rlen = read(xfds, &xxxidx, sizeof(struct xxxidx));

if (rlen != sizeof(struct xxxidx))

    {

printf("rlen failed\n");

return -1;

}

 

xsiz = xxxidx.recs;

 

xoff = lseek(xfds, 0L, SEEK_END);

maxr = (xoff - sizeof(struct xxxidx)) / xsiz;

if (maxr <= 0) {

printf("maxr failed\n");

return -1;

}

 

xoff = sizeof(struct xxxidx);

cnt = lseek(xfds, xoff, SEEK_SET);

 

for (ii = 0; ii < maxr ; ii++)

{

rlen = read(xfds, buff, xsiz);

 

tmpdjd = (struct biglotTrade *)buff;

 

if (strcmp(tmpdjd->tradeId,a1)==0 &&

          strcmp(tmpdjd->dealId,a2)==0)

{

xoff = sizeof(struct xxxidx) + (ii * xsiz);

cnt = lseek(xfds, xoff, SEEK_SET);

 

tmpdjd->typeOfTrade = 1; //UPDATE DATA 

wlen = write(xfds, tmpdjd, sizeof(struct biglotTrade));

printf("wlen = %d\n", wlen);

 

break;

}

}

return 0;

}

 

+ Recent posts