페이지

2014년 3월 27일 목요일

when crontab not working

when crontab not working


  1. check cron log
    1. /var/log/cron
  2. check mail and find the error and correct the error
    1. /var/spool/mail/userId

cross site scripting(XSS) defend code in java

following code are used to defend XSS attack




1.

public static String getXSSCheck(String strTemp){
        if (strTemp == null || strTemp == "")
            return "";

        strTemp = replace(strTemp, "#", "&#35"); //1
        strTemp = replace(strTemp, "&", "&#38"); //2
        strTemp = replace(strTemp, "&#38#35", "&#35"); // 1번 처리 이후 생긴 &를 2번에서 재수정하여 보정

        strTemp = replace(strTemp, "<", "&lt;");
        strTemp = replace(strTemp, ">", "&gt;");
        strTemp = replace(strTemp, "(", "&#40");
        strTemp = replace(strTemp, ")", "&#41");
        strTemp = replace(strTemp, "\"", "&#34");
        strTemp = replace(strTemp, "/", "&#47");
        strTemp = replace(strTemp, "?", "&#92");
        strTemp = replace(strTemp, ":", "&#59");
        strTemp = replace(strTemp, "\n", "&#10"); //line feed
        strTemp = replace(strTemp, "\r", "&#13"); //carriage return

        return strTemp;
    }








2.map data 일괄적용

  /**
     * XSS체크 일괄 적용
     * @param 
     * @return String
     */
    public static LData getAdjustedXSSData(LData data){
        Object[] obj = data.getKeys();
        for(int i=0;i < obj.length;i++){
            String tmp = (String)obj[i];
            data.setString(tmp, StringUtil.getXSSCheck(data.getString(tmp)));
            
        }
        return data;
    }
    

2014년 3월 26일 수요일

네트워크 프로그래밍

프로세스간 통신
 - 파이프 - 데이터를 주고받기위해선 파이프를 2개 이상 사용(sleep같은건 안좋음)
  - 멀리 프로세스(게임)  vs 멀리플렉싱(채팅)
입출력 함수 (send,recv함수)
 - MSG_OOB, MSG_PEEK, MSG_DONTWAIT

2014년 3월 25일 화요일

[altibase]how to make function

  • how to make sql function in altibase
CREATE OR REPLACE FUNCTION FUN_GET_CODE_NAME (STR_CODE_TYPE IN VARCHAR(20), STR_CODE IN VARCHAR(20))
RETURN VARCHAR(100)
IS
  RET_CODE VARCHAR(100);
BEGIN
  select CODE_NAME INTO RET_CODE 
  from table_name
    where code_type=str_CODE_TYPE
    AND CODE=str_CODE
    AND USE_YN='Y';
  
    RETURN RET_CODE;
    
    EXCEPTION   
    WHEN NO_DATA_FOUND THEN  
      RETURN '';  
END;


  • how to call the function
SELECT FUN_GET_CODE_NAME('A0', 'A2') FROM DUAL;

when ! comes in contents

느낌표가 나오면서 컨텐츠가 깨지면
/etc/mail/sendmail.cf을 열어서 다음부분의 L값을 바꿔준다


#####################################
###   SMTP Mailer specification   ###
#####################################

#####  @(#)smtp.m4      8.38 (Berkeley) 5/19/1998  #####

Msmtp,          P=[IPC], F=mDFMuX, S=11/31, R=21, E=\r\n, L=990,
                T=DNS/RFC822/SMTP,
                A=IPC $h
Mesmtp,         P=[IPC], F=mDFMuXa, S=11/31, R=21, E=\r\n, L=990,
                T=DNS/RFC822/SMTP,
                A=IPC $h
Msmtp8,         P=[IPC], F=mDFMuX8, S=11/31, R=21, E=\r\n, L=990,
                T=DNS/RFC822/SMTP,
                A=IPC $h
Mrelay,         P=[IPC], F=mDFMuXa8, S=11/31, R=61, E=\r\n, L=2040,
                T=DNS/RFC822/SMTP,
                A=IPC $h

[study]network programing

time-wait
nagle 알고리즘
다중접속 서버
fork 함수 - 프로세스를 복제한다
좀비 프로세스 - 프로세스 종료 후 메모리상에서 사라지지 않는 프로세스
시그널 핸들링
프로세스 기반의 다중접속 서버구현

2014년 3월 24일 월요일

[altibase]create or drop table space



  • directory 생성
mkdir -p /alti_dbs_disk0/disk_dat
mkdir -p /alti_dbs_disk0/disk_idx
mkdir -p /alti_dbs_mem0/mem_dat_0/
mkdir -p /alti_dbs_mem1/mem_dat_1/

  • DISK DATA 생성
CREATE DISK DATA TABLESPACE TS_TMP_DISK_DAT
DATAFILE
'/alti_dbs_disk0/disk_dat/TMP_disk_dat_01.dbf'
SIZE 1G
AUTOEXTEND OFF;


  • DISK IDX 생성
CREATE DISK DATA TABLESPACE TS_TMP_DISK_IDX
DATAFILE
'/alti_dbs_disk0/disk_idx/TMP_disk_idx_01.dbf'
SIZE 1G
AUTOEXTEND OFF


  • MEM DATA 생성
CREATE MEMORY TABLESPACE TS_TMP_MEM_DAT
      SIZE 64M 
      AUTOEXTEND ON NEXT 20M MAXSIZE 2G 
      CHECKPOINT PATH '/alti_dbs_mem0/mem_dat_0/',
'/alti_dbs_mem1/mem_dat_1/';

또는

CREATE MEMORY TABLESPACE TS_SPI_MEM_DAT
      SIZE 300M 
      AUTOEXTEND ON 


  • drop tablespace


DROP TABLESPACE TS_TMP_MEM_DAT INCLUDING CONTENTS CASCADE CONSTRAINTS;

DROP TABLESPACE TS_TMP_DISK_IDX INCLUDING CONTENTS CASCADE CONSTRAINTS;

DROP TABLESPACE TS_TMP_DISK_DAT INCLUDING CONTENTS CASCADE CONSTRAINTS;




2014년 3월 20일 목요일

소켓 프로그램 소스 샘플(서버, 클라이언트)

다음은 간단한 소켓 프로그램 서버와 클라이언트의 소스이다
해보니 그냥 일반 jsp와 다를바 없어 보인다


  • server source

/*
 * helloworld_server.c
 * Written by SW. YOON
 */


#include <stdio.h>

#include <stdlib.h>

#include <string.h>

#include <unistd.h>

#include <arpa/inet.h>

#include <sys/types.h>

#include <sys/socket.h>



void error_handling(char *message);

int main(int argc, char **argv)
{
    int serv_sock;
    int clnt_sock;
    struct sockaddr_in serv_addr;
    struct sockaddr_in clnt_addr;
    int clnt_addr_size;
    char message[]="Hello World!\n";
    
    if(argc!=2){
        printf("Usage : %s <port>\n", argv[0]);
        exit(1);
    }
    
    serv_sock=socket(PF_INET, SOCK_STREAM, 0); /* 서버 소켓 생성 */
    if(serv_sock == -1)
        error_handling("socket() error");
    
    memset(&serv_addr, 0, sizeof(serv_addr));
    serv_addr.sin_family=AF_INET;
    serv_addr.sin_addr.s_addr=htonl(INADDR_ANY);
    serv_addr.sin_port=htons(atoi(argv[1]));
    
    if( bind(serv_sock, (struct sockaddr*) &serv_addr, sizeof(serv_addr))==-1 ) /* 소켓에 주소 할당 */
        error_handling("bind() error"); 
    
    if( listen(serv_sock, 5)==-1 )  /* 연결 요청 대기 상태로 진입 */
        error_handling("listen() error");
    
    for(;;){

        clnt_addr_size=sizeof(clnt_addr);  
        clnt_sock=accept(serv_sock, (struct sockaddr*)&clnt_addr,&clnt_addr_size); /* 연결 요청 수락 */
        if(clnt_sock==-1)
            error_handling("accept() error");  
        
        write(clnt_sock, message, sizeof(message)); /* 데이터 전송 */  
        printf("Message in server : %s \n", message);  
        close(clnt_sock); /* 연결 종료 */
    }
    return 0;
    

    }


        
    void error_handling(char *message)
{
    fputs(message, stderr);
    fputc('\n', stderr);
    exit(1);

    }



client source
/*
 * helloworld_client.c
 * Written by SW. YOON
 */


    #include <stdio.h>

    #include <stdlib.h>

    #include <string.h>

    #include <unistd.h>

    #include <arpa/inet.h>

    #include <sys/types.h>

    #include <sys/socket.h>


    
    void error_handling(char *message);


    
    int main(int argc, char **argv)
{
    int sock;
    struct sockaddr_in serv_addr;
    char message[30];
    int str_len;
    
    if(argc!=3){
        printf("Usage : %s <IP> <port>\n", argv[0]);
        exit(1);
    }
    
    sock=socket(PF_INET, SOCK_STREAM, 0);  /* 서버 접속을 위한 클라이언트 소켓 생성 */
    if(sock == -1)
        error_handling("socket() error");
    
    memset(&serv_addr, 0, sizeof(serv_addr));
    serv_addr.sin_family=AF_INET;
    serv_addr.sin_addr.s_addr=inet_addr(argv[1]);
    serv_addr.sin_port=htons(atoi(argv[2]));
        
    if(connect(sock, (struct sockaddr*)&serv_addr, sizeof(serv_addr))==-1) /* 서버로 연결 요청 */
        error_handling("connect() error!");
    
    str_len=read(sock, message, sizeof(message)-1); /* 데이터 수신 */
    if(str_len==-1)
        error_handling("read() error!");
    
    message[str_len]=0;
    printf("Message from server : %s \n", message);  
    close(sock); /* 연결 종료 */
    
    return 0;
}


        
    void error_handling(char *message)
{
    fputs(message, stderr);
    fputc('\n', stderr);
    exit(1);
}


다 하고 나서 컴파일은
gcc serverHello.c -o server
gcc client.c -o client

이렇게 하고 서버 먼저 실행하고 클라이언트에서 접속해보면 된다



출처 : tcp/ip 소켓 프로그래밍 책에서...

sendmail client source

MakeContentsAndSend.java

public class MakeContentsAndSend {
    
    public static void main(String[] args) throws Exception {
        MakeContentsAndSend.sendTemporaryPassword("scoutreturns");
    }
    
    
     
    public static void sendContents(String str1) throws Exception{
        
        StringBuffer content = new StringBuffer();
        content.append("<html>");
        content.append("<head>");
        content.append("<meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\" />");
        content.append("<meta charset=\"utf-8\" />");
        content.append("<title> test </title>");
        content.append("</head>");
        
        content.append("<body>");
        content.append("<table width=600 class=MsoTableGrid border=0 cellspacing=0 cellpadding=0 style='border-collapse:collapse;border:none'>");
        content.append("<tr>");
        content.append("<td align=center height=30>");
        content.append("<b><span style='font-size:14pt'>메일 테스트</span><b>");
        content.append("</td>");
        content.append("</tr>");
        content.append("<tr>");
        content.append("<td style='height:2pt; background:silver'>");
        content.append("</td>");
        content.append("</tr>");
        content.append("</table>");
        content.append("<br><br>");
        content.append("</body>");
        content.append("</html>");
        
      
        new MailSend( "111.222.333.444", 
                      "fromName", 
                      "toName" ,
                      "fromEmail", 
                      "toEmail" ,
                      "title" ,
                      content.toString()).send();
    }
}


MailSend.java

import java.net.*;
import java.io.*;

public class MailSend {
    
    private static String smtpServer    = null;
    private static String sendNm        = null;
    private static String rcptNm        = null;
    private static String sendId        = null;
    private static String rcptId        = null;
    private static String title         = null;
    private static String content       = null;

    public MailSend(
        String _smtpServer, 
        String _sendNm, 
        String _rcptNm, 
        String _sendId, 
        String _rcptId, 
        String _title, 
        String _content
    ) {
        this.smtpServer = _smtpServer;
        this.sendNm     = _sendNm;
        this.rcptNm     = _rcptNm;
        this.sendId     = _sendId;
        this.rcptId     = _rcptId;
        this.title      = _title;
        this.content    = _content;
    }

    public synchronized int send() throws Exception {

        Socket socket=new Socket(smtpServer, 25);
        BufferedReader br=new BufferedReader(new InputStreamReader( socket.getInputStream(),"EUC-KR" ) );
        PrintWriter pw=new PrintWriter( new OutputStreamWriter(socket.getOutputStream(),"EUC-KR"), true );
        
        System.out.println("서버에 연결되었습니다.");
        
        String line=br.readLine();
        System.out.println("응답:"+line);
        
        if (!line.startsWith("220")) {
            //throw new Exception("SMTP서버가 아닙니다:"+line);
            System.out.println("SMTP서버가 아닙니다:"+line);
            return 1;
        }


/*
        System.out.println("HELO 명령을 전송합니다.");
        pw.println("HELO");
        line=br.readLine();
        System.out.println("응답:"+line);
        if (!line.startsWith("250")) throw new Exception("HELO 실패했습니다:"+line);
*/
        System.out.println("MAIL FROM 명령을 전송합니다.");
        
        pw.println("mail from : <AAA:"+sendId+"@test.co.kr>");
        
        line=br.readLine();
        
        System.out.println("응답:"+line);
        
        if (!line.startsWith("250")) {
            //throw new Exception("MAIL FROM 에서 실패했습니다:"+line);
            System.out.println("MAIL FROM 에서 실패했습니다:"+line);
            return 2;
        }
        
        System.out.println("RCPT 명령을 전송합니다.");
        pw.println("rcpt to : "+rcptId);
        line=br.readLine();
        System.out.println("응답:"+line);
        if (!line.startsWith("250")) {
            //throw new Exception("RCPT TO 에서 실패했습니다:"+line);
            System.out.println("RCPT TO 에서 실패했습니다:"+line);
            return 3;
        }
        
        System.out.println("DATA 명령을 전송합니다.");
        pw.println("data 제목");
        line=br.readLine();
        System.out.println("응답:"+line);
        if (!line.startsWith("354")) {
            //throw new Exception("DATA 에서 실패했습니다:"+line);
            System.out.println("DATA 에서 실패했습니다:"+line);
            return 4;
        }
        
        System.out.println("본문을 전송합니다.");
        pw.println("From: "+sendNm+" <"+sendId+">");
        pw.println("To: "+rcptNm+" <"+rcptId+">");
        pw.println("Subject: "+title);
        pw.println("Content-Type: text/html;");
        
        //pw.println(content);
        pw.println("\r");
        pw.println(content);
        pw.println(".");
        line=br.readLine();
        System.out.println("응답:"+line);
        if (!line.startsWith("250")) {
            //throw new Exception("내용전송에서 실패했습니다:"+line);
            System.out.println("내용전송에서 실패했습니다:"+line);
            return 5;
        }
        
        System.out.println("접속 종료합니다.");
        pw.println("quit");
        
        br.close();
        pw.close();
        socket.close();
        
        return 0;
    }
    
  
  
}

[sendmail]when cannot connection from remort host and cannot send mail


  • 원격에서 sendmail 접속 안될때
    • reason : For security reason sendmail is by default configured to accept connection from local system (127.0.0.1). This should avoid open mail relay problem.
    • solution :
# vi /etc/mail/sendmail.mc
      • find following sentence 
                         DAEMON_OPTIONS(`Port=smtp,Addr=127.0.0.1, Name=MTA')dnl
      • and comment or remove above line and insert new line that read as follows:
                         DAEMON_OPTIONS(`Port=smtp,Name=MTA')dnl
      • Above line will force to accept connection from any host. Save the file. Regenerate sendmail configuration file using m4:
# m4 /etc/mail/sendmail.mc > /etc/mail/sendmail.cf
# /etc/init.d/sendmail restart



  • 그런데 이때 다음과 같은 에러가 발생 할 수 도 있다.
    -m4: m4 /etc/mail/sendmail.mc > /etc/mail/sendmail.cf /etc/mail/sendmail.mc:10: m4: Cannot open /usr/share/sendmail-cf/m4/cf.m4:
    • solution : This errors simply means you do not have the sendmail-cf package installed. 암튼 위 패키지를 설치하면 된다

  • 다 하고 났는데 이제는 클라이언트에서 메일 접속하고 발생할 때 access deny가 나온다.
    • solution
  • 그래도 안되면 다음파일열어서 전부 주석처리
    • vi /etc/mail/local-host-names
1) access파일 열어서 아이피 추가

# vi /etc/mail/access

# Check the /usr/share/doc/sendmail/README.cf file for a description
# of the format of this file. (search for access_db in that file)
# The /usr/share/doc/sendmail/README.cf is part of the sendmail-doc
# package.
#
# If you want to use AuthInfo with "M:PLAIN LOGIN", make sure to have the
# cyrus-sasl-plain package installed.
#
# By default we allow relaying from localhost...
Connect:localhost.localdomain           RELAY
Connect:localhost                       RELAY
Connect:127.0.0.1                       RELAY
Connect:999.99.99.99                  RELAY   <- 이런식으로 아이피 추가

2)
# /usr/sbin/makemap hash /etc/mail/access < /etc/mail/access





2014년 3월 19일 수요일

네트워크 프로그램


네트워크가 모여서 인터넷이 된다

네트워크와 네트워크를 연결해주는 것이 라우터

서버오와 클라이언트는 프로그램이지 머신이 아닌다

네트워크프로그래밍이랑 소켓이란 의미랑 일반적으로 같이 쓴다

소켓은 장치임

low-level - 운영체제가 제공해주는

리눅스에서는 모든것을 다 파일로 관리
 - 파일을 생성하던, 소켓을 생성하던 관리하는것은 리눅스이고, 둘 다 파일로 간주 한다.

 그래서 파일 입출력 함수인 read나 write를 소켓에서도 고대로 갔다 쓸 수 있다

 데이터 전송하는 것은 출력이고, 입력 받는것은 수신, 즉 전송=출력이고 수신이 입력이다


tcp/ip 프로토콜 스택 -> 프로토콜을 쌓아놓은 것




divide and conqure


 소켓, 파일 디스크립터, 프로토콜

[devon]dynamic query 비교값

조건문비교값
GE>=
GT>
LE
LT<
EQ==
NE!=
EMPTY값이 없을 경우
NULLNULL인 경우
NOTNULLNot null인 경우
NOTEMPTY값이 있을 경우
NONEnull이거나 빈 스트링인 경우
NOTNONEnull이 아니고 빈 스트링이 아닌 경우


항목역할 및 기능
statement name사용할 SQL문의 이름
append / replace조건에 따라 query문에 append / replace
whereWhere를 붙일지 여부. True인 경우 where를 붙임(생략할 경우 false)
condition체크할 조건. EQ:”=” GE:”>=” LE:”?” GT:”>” LT:”<” EMPTY:”” NE:”!=” NULL:null NOTEMPTY:”값이 존재” 위의 조건으로 좌측에 정의된 값과 dn측에 정의된 값을 비교하여 맞을 경우 정의된 append, replace를 시행한다. 단 EMPTY와 NOTEMPTY, NULL인 경우는 좌측 값만 기술한다. 비교해야 할 값이 두 개 이상인 경우 and(&), or연산이 가능하다.
idappend나 replace할 부분의 id

예제)
<statement name="retrieveBookMasterList"
  <![CDATA[ 
  SELECT {#2} a.bookid
       , a.booknm, {/#2} a.author
       , a.description 
    FROM bookmaster a
       , codemng    b 
   WHERE age = ?
     AND address = ? 
     AND a.bookid = b.id 
    {#1} 
  ]]> 
  <append where="true" condition="(${name}.NOTEMPTY&amp;${age}.GE.5)||${name}.EQ.park" id="#1"
    AND age > 5 
  </append
  <replace condition="${age}.NOTEMPTY" id="#2"
    a.bookid 
  </replace
</statement>

image

image