/* Processed by ecpg (15.18 (Debian 15.18-0+deb12u1)) */
/* These include files are added by the preprocessor */
#include <ecpglib.h>
#include <ecpgerrno.h>
#include <sqlca.h>
/* End of automatic include section */

#line 1 "app/online/mg_ol_0004.pgc"
/* @tier easy @module mg @transform msg-gateway-online */
/*
 * mg_ol_0004.pgc - 채널 인증/세션 개설 서비스 (MG_OL_0004)  [tier=easy]
 *
 * 채널ID(CHANID)와 비밀키(SECRET)를 tx_buf 로 받아 간이 해시(FNV-1a 변형)
 * 로 무결성을 검증하고, 통과 시 현재 트랜잭션ID(tx_current_xid)를 섞어
 * 세션토큰을 발급한다. 실패 시 인증오류 응답을 반환한다.
 */
#include <stdio.h>
#include <string.h>

#include "txcore.h"
#include "txcore_dbio.h"
#include "acq_util.h"
#include "mg_core.h"


#line 1 "/usr/include/postgresql/sqlca.h"
#ifndef POSTGRES_SQLCA_H
#define POSTGRES_SQLCA_H

#ifndef PGDLLIMPORT
#if  defined(WIN32) || defined(__CYGWIN__)
#define PGDLLIMPORT __declspec (dllimport)
#else
#define PGDLLIMPORT
#endif							/* __CYGWIN__ */
#endif							/* PGDLLIMPORT */

#define SQLERRMC_LEN	150

#ifdef __cplusplus
extern "C"
{
#endif

struct sqlca_t
{
	char		sqlcaid[8];
	long		sqlabc;
	long		sqlcode;
	struct
	{
		int			sqlerrml;
		char		sqlerrmc[SQLERRMC_LEN];
	}			sqlerrm;
	char		sqlerrp[8];
	long		sqlerrd[6];
	/* Element 0: empty						*/
	/* 1: OID of processed tuple if applicable			*/
	/* 2: number of rows processed				*/
	/* after an INSERT, UPDATE or				*/
	/* DELETE statement					*/
	/* 3: empty						*/
	/* 4: empty						*/
	/* 5: empty						*/
	char		sqlwarn[8];
	/* Element 0: set to 'W' if at least one other is 'W'	*/
	/* 1: if 'W' at least one character string		*/
	/* value was truncated when it was			*/
	/* stored into a host variable.             */

	/*
	 * 2: if 'W' a (hopefully) non-fatal notice occurred
	 */	/* 3: empty */
	/* 4: empty						*/
	/* 5: empty						*/
	/* 6: empty						*/
	/* 7: empty						*/

	char		sqlstate[5];
};

struct sqlca_t *ECPGget_sqlca(void);

#ifndef POSTGRES_ECPG_INTERNAL
#define sqlca (*ECPGget_sqlca())
#endif

#ifdef __cplusplus
}
#endif

#endif

#line 17 "app/online/mg_ol_0004.pgc"


TX_SERVICE(MG_OL_0004, ctx)
{
    char          chanid[24];
    char          secret[40];
    char          expect[24];
    char          token[40];
    unsigned long h;
    unsigned long xid;
    int           i;

    tx_log(TX_LOG_INFO, "[MG_OL_0004] 채널 인증/세션 개설 서비스 진입");

    /* 1) 인증 요소 수신 */
    if (tx_buf_get(ctx->in, "CHANID", chanid, sizeof(chanid)) != TX_OK ||
        tx_buf_get(ctx->in, "SECRET", secret, sizeof(secret)) != TX_OK ||
        chanid[0] == '\0' || secret[0] == '\0') {
        tx_log(TX_LOG_ERROR, "[MG_OL_0004] 인증요소(CHANID/SECRET) 누락");
        tx_return(ctx, TX_EINVAL, ctx->out);
        return;
    }

    /* 2) 채널ID+비밀키 결합에 대한 간이 해시 산출 (FNV-1a 변형) */
    h = 2166136261UL;
    for (i = 0; chanid[i] != '\0'; i++) {
        h ^= (unsigned char)chanid[i];
        h *= 16777619UL;
    }
    h ^= (unsigned char)':';
    h *= 16777619UL;
    for (i = 0; secret[i] != '\0'; i++) {
        h ^= (unsigned char)secret[i];
        h *= 16777619UL;
    }

    /* 3) 기대 인증값(EXPECT)이 함께 오면 대조, 아니면 산출값을 그대로 신뢰 */
    snprintf(token, sizeof(token), "%08lx", (h & 0xffffffffUL));
    if (tx_buf_get(ctx->in, "EXPECT", expect, sizeof(expect)) == TX_OK &&
        expect[0] != '\0') {
        if (strncmp(expect, token, 8) != 0) {
            tx_log(TX_LOG_WARN, "[MG_OL_0004] 인증 불일치 chan=%s exp=%s calc=%s",
                   chanid, expect, token);
            tx_buf_reset(ctx->out);
            tx_buf_sets(ctx->out, "RESP", RESP_INVALID);
            tx_buf_sets(ctx->out, "REASON", "AUTHFAIL");
            tx_return(ctx, TX_FAIL, ctx->out);
            return;
        }
    }

    /* 4) 세션토큰 발급: 해시 상위워드 + 현재 XID 하위워드 결합 */
    xid = (unsigned long)tx_current_xid();
    snprintf(token, sizeof(token), "%s-%04lx%04lx",
             chanid, (h >> 16) & 0xffffUL, xid & 0xffffUL);

    /* 5) 세션 개설 응답 */
    tx_buf_reset(ctx->out);
    tx_buf_sets(ctx->out, "RESP", RESP_OK);
    tx_buf_sets(ctx->out, "CHANID", chanid);
    tx_buf_sets(ctx->out, "SESSION", token);
    tx_buf_setlong(ctx->out, "XID", (long)xid);
    tx_buf_setlong(ctx->out, "AUTHHASH", (long)(h & 0x7fffffffUL));

    /* 6) 발급 세션을 세션 테이블(mg_session)에 개설상태('O')로 임베디드 SQL 등록 */
    {
        /* exec sql begin declare section */
         
         
         
        
#line 84 "app/online/mg_ol_0004.pgc"
 char h_sess_token [ 40 ] ;
 
#line 85 "app/online/mg_ol_0004.pgc"
 char h_sess_chan [ 24 ] ;
 
#line 86 "app/online/mg_ol_0004.pgc"
 long h_sess_xid ;
/* exec sql end declare section */
#line 87 "app/online/mg_ol_0004.pgc"


        strncpy(h_sess_token, token, sizeof(h_sess_token) - 1);
        h_sess_token[sizeof(h_sess_token) - 1] = '\0';
        strncpy(h_sess_chan, chanid, sizeof(h_sess_chan) - 1);
        h_sess_chan[sizeof(h_sess_chan) - 1] = '\0';
        h_sess_xid = (long)xid;

        if (tx_begin() == TX_OK) {
            { ECPGdo(__LINE__, 0, 1, NULL, 0, ECPGst_normal, "insert into mg_session ( session_token , chan_id , xid , sess_status ) values ( $1  , $2  , $3  , 'O' )", 
	ECPGt_char,(h_sess_token),(long)40,(long)1,(40)*sizeof(char), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, 
	ECPGt_char,(h_sess_chan),(long)24,(long)1,(24)*sizeof(char), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, 
	ECPGt_long,&(h_sess_xid),(long)1,(long)1,sizeof(long), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, ECPGt_EOIT, ECPGt_EORT);}
#line 98 "app/online/mg_ol_0004.pgc"

            if (sqlca.sqlcode != TX_SQL_OK) {
                TX_DBIO_LOG_ERR("INSERT mg_session");
                tx_abort();
            } else {
                tx_commit();
            }
        }
    }

    tx_log(TX_LOG_INFO, "[MG_OL_0004] 세션 개설완료 chan=%s session=%s", chanid, token);
    tx_return(ctx, TX_OK, ctx->out);
}
