June 10, 2020

What is REST(Representational State Transfer)


❑ REST(Representational State Transfer)
❍ Communication way of client↔server.
클라이언트↔서버의 통신 방식.
❍ An architecture style (type) for the purpose of communication using URI and HTTP.
URI와 HTTP를 이용한 통신 목적의 아키텍처 스타일(유형).
* URI(Uniform Resource Identifier): Name for identifying resources such as pictures, documents and videos.
그림, 영상 등의 자원 식별용 이름.
* Architecture style(아키텍처 스타일): Type of architecture(structure). 아키텍처(구조)의 종류(유형, 스타일, 타입).
e.g.
Client-Server(클라이언트/서버)
Repository(저장소)
Pipe/Filter(파이프/필터)
REST.

❑ RESTful: REST applied system.
REST가 적용된 시스템.

❑ REST API: REST applied API.
REST가 적용된 API.

❑ The system that provides REST API is RESTful.
REST API를 제공하는 시스템은 RESTful이다.




To be precise, REST should satisfy the following conditions.
정확하게는, REST는 아래 조건을 만족해야 한다.

1. Uniform interface: It conforms to the interface specified by URI use, HTTP method use, RPC not called, etc.

1. 일관된 인터페이스(Uniform interface): URI 사용, HTTP 메소드 사용, RPC 미호출 등으로 지정된 인터페이스를 준수한다.



2. Client-Server: The client sends a request message to the server, and the server sends a response message about the request.

2. 클라이언트/서버(Client-Server): 클라이언트는 서버에 요청(request) 메시지를 전송하고 서버는 요청에 대한 응답(response) 메시지를 전송한다.



3. Statelessness: Communication is possible without a previous situation(context) such as a session.

3. 비연결성(Statelessness): 세션 등 이전 상황(문맥) 없이도 통신할 수 있다.



4. Cacheable: The server's response message can be cached (stored and reused).

4. 캐시 가능(Cacheable): 서버의 응답 메시지는 캐싱(저장 후 재사용)될 수 있다.



5. Layered system: Roles are separated by hierarchy. Therefore, even if roles (load balancing, authentication, etc.) are added/removed in the middle, communication is not affected.

5. 계층화된 시스템(Layered system): 계층별로 기능이 분리된다. 그러므로 중간에 기능(로드 밸런싱, 인증 등)이 추가/제거되어도 통신에 영향을 주지 않는다.



6. Code on demand(option): For easy data processing, the server can send a script to be executed on the client.

6. 주문형 코드(Code on demand)(선택): 손쉬운 데이터 처리를 위해 서버는 클라이언트에서 실행될 스크립트를 전송할 수 있다.

May 02, 2020

CORS and JavaScript.

This summary is not available. Please click here to view the post.

September 02, 2019

How to check each memory address

Let's check the address of the text, data, BSS, heap, libc, and stack memory addresses with C code.

C 코드를 통해 Text, data, BSS, heap, libc, stack 메모리 영역의 주소를 확인한다.

// < check.c >

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dlfcn.h>

void aFunc() {
    printf("Function called");
}

char *global1 = "glob1";
char global2;

int main(){
    char *heap = malloc(128);
    void *tmp;
    long libcAddr;
    tmp = dlopen("/lib/libc.so.6", RTLD_LAZY);
    libcAddr = (long)dlsym(tmp, "scanf");

    printf("[Text]  %p\n", aFunc);
    printf("[Data]  %p\n",global1);
    printf("[BSS]   %p\n",&global2);
    printf("[Heap]  %p\n", heap);
    printf("[Libc]  %p\n", libcAddr);
    printf("[Stack] %p\n", &libcAddr);

    return 0;
}

How to compile.
컴파일 방법.

gcc -o check check.c -lc -ldl

- lc: Load the library "libc.so" before loading "libdl.so".
"libdl.so"를 로드하기 전 "libc.so"를 로드.

- ldl: Load the library "libdl.so".
"libdl.so" 라이브러리 로드.

root@ubuntu:~# ./check
[Text]  0x400736
[Data]  0x4008d4
[BSS]   0x601061
[Heap]  0x602010
[Libc]  0x7ffff7a777e0
[Stack] 0x7fffffffe580

July 01, 2019

How to create HTTP request message(crawling) using Python



#-*- coding: utf-8 -*-

import sys
import os
import ssl
from socket import *

def main(argv):

    rstCrawl = crawl("news.naver.com", 443, "/main/main.nhn", "?mode=LSD&mid=shm&sid1=102") 
    # os.system("Pause") 
 
 
def crawl(dHost, target_port="80", path="/", paramGET=""):
     
    # 소켓 준비.
    print("  (Notice) Prepare the socket.")
    client = socket(AF_INET, SOCK_STREAM)
    if (target_port == 80):
        s_sock = client
    elif (target_port == 443):
        context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
        s_sock = context.wrap_socket(client, server_hostname=dHost)
    s_sock.connect((dHost, target_port))
   
    # 송신용 요청 메시지 준비.
    print("  (Notice) Prepare the request message.")
    request = "GET "+ path + paramGET +" HTTP/1.1\r\n"
    request += "Host:" + dHost + "\r\n"
    request += "\r\n"
 
    # 반복: 디코딩 성공 시 탈출.
    flagBreakDecode = False
    while(flagBreakDecode == False):
 
        s_sock.send(request.encode())
     
        # 반복: 데이터 수신 완료 시 탈출.
        httpResponse = b""
        flagBreakRecv = False
        while(flagBreakRecv == False):
            tmpHttpResponse = s_sock.recv(4096)
            if ("0\\r\\n\\r\\n" in str(tmpHttpResponse)) == True:
                flagBreakRecv = True
            httpResponse += tmpHttpResponse
     
        httpResponseLen = len(httpResponse)
        print("  (Notice) Recieved data(Byte):", httpResponseLen)
 
        try:
            dHttpResponse = httpResponse.decode("euc-kr")
            # dHttpResponse = httpResponse.decode()
            flagBreakDecode = True
            print("  (Notice) Complete decoding.")
        except UnicodeDecodeError:
            print("  (Error) UnicodeDecodeError. → Modify the way of decoding.")
            continue
         
    # charset 제거: 한글 식별 목적. 
    dHttpResponse = dHttpResponse.replace("<meta charset=\"utf-8\">", "")
    dHttpResponse = dHttpResponse.replace("<meta charset=\"euc-kr\">", "")

    # 결과 출력
    with open("./" + dHost + "_crawl.html", "w", encoding="utf-8") as f:
        f.write(dHttpResponse)

    print("  (Notice) Complete crawl.")
    return dHttpResponse
 
 
if __name__ == '__main__':
    main(sys.argv)

When the above Python program is executed, the file "xxx_crawl.html" is created in the same location.

위 파이썬 프로그램을 실행하면, 동일 위치에 "xxx_crawl.html" 파일이 생성된다.

June 21, 2019

How to use python pdb



❑ pdb: The Python debugger. 파이썬 디버거.

❑ How to debug.
01. Command line style.    커맨드 라인 방식.
python -m pdb [program.py]

02. Python code style.    파이썬 코드 방식.
import pdb

pdb.set_trace()  
# Place this code in the position you want to stop. But it is not recognized as a breakpoint.
# 중단하고 싶은 위치에 이코드를 넣는다. 하지만 브레이크포인트로 인정되지는 않는다.

❑ Usage.    사용법.
CommandDescription
?
h(help)
Print help.
도움말 출력.
n(next)Step over.
스탭 오버.
s(step)Step into.
스탭 인투.
c(continue)Execute continuously until a breakpoint is encountered.
다음 중단점까지 실행.
r(return)Execute continuously until the current function returns.
현재 함수가 값을 반환할 때까지 실행.
l(list) [line], [line]Print the 11 lines around the current line, If no line is specified.
라인을 지정하지 않으면 현재 위치 주위의 11개 라인 출력.

* list 15, 19
Print 15~19 lines.
15~19라인 출력.
b(break) [line | function], [condition]Set a breakpoint.
브레이크포인트 설정.

* b
Print all breakpoints set up to now.
현재까지 설정된 브레이크포인트 출력.

* b 9
Set a breakpoint at the line 9.
9라인에 breakpoint 설정.

* b main
Set a breakpoint at the main() function.
main() 함수에 브레이크포인트 설정.

* b 9, var1>0
Set a breakpoint that stops if the value of var1 is greater than zero.
var1의 값이 0보다 크면 정지하는 브레이크포인트 설정.
enable [number]Enable a breakpoint.
브레이크포인트를 활성화.

* enable 1
Enable the breakpoint #1.
1번 브레이크포인트를 활성화.
disable [number]Disable a breakpoint.
브레이크포인트를 비활성화.

* disable 1
Disable the breakpoint #1.
1번 브레이크포인트를 비활성화.
cl(clear) [number]Delete a breakpoint.
브레이크포인트 제거

* cl 1
Delete the breakpoint #1.
1번 브레이크포인트 제거.
bt
w(where)
Print a stack trace(function call).
스택 추적 결과 출력(함수 호출).
u(up)Based on stack trace results, move to the higher(older) stack frame.
스택 추적 결과를 기준으로, 상위(오래된) 스택 프레임으로 이동.
d(down)Based on stack trace results, move to lower(newer) stack frame.
스택 추적 결과를 기준으로, 하위(최신의) 스택 프레임으로 이동.
a(args)Print the arguments of the current function.
현재 위치의 함수에 입력된 아규먼트 값들을 출력.
[Python code]Execute Python code.
파이썬 코드 실행.


January 12, 2019

Dark web, deep web, surface web

❑ Dark web: The cyberspace accessible only through specific software or authentication.
다크 웹: 특정 소프트웨어나 인증을 통해서만 접근할 수 있는 사이버 공간.

❑ Deep web: The cyberspace that search engines such as Google can not access. It is a superordinate concept including Dart web.
딥 웹: 구글 등 검색 엔진이 접근할 수 없는 사이버 공간. 다크 웹을 포함하는 상위개념.

❑ Surface web: The cyberspace that search engines such as Google can access.
서피스 웹: 구글 등 검색 엔진이 접근할 수 있는 사이버 공간.

December 30, 2018

RDBMS meta-data

❑ Meta-data: The data to describe the data in the DB.
메타데이터: DB의 데이터를 설명하기 위한 데이터.


❑ MySQL, PostgreSQL: INFORMATION_SCHEMA(DB format. DB 형태.)
INFORMATION_SCHEMA.COLUMNS
PropertyData typeDescription
COLUMN_NAMEvarchar(64)The column's name.
칼럼의 이름.
TABLE_NAMEvarchar(64)The table's name to which the column belongs.
칼럼이 속해있는 테이블의 이름.
TABLE_SCHEMAvarchar(64)The database's name that contains the table to which the column belongs.
칼럼이 속해있는 테이블이 저장된 데이터베이스의 이름.




❑ SQLite: SQLITE_MASTER(table format. 테이블 형태.)
SQLITE_MASTER
PropertyData typeDescription
TYPEtextThe object type. 객체의 종류(table, view, trigger, index).
NAMEtextThe object's name
오브젝트의 이름.
TBL_NAMEtextThe name of a view or a table.
뷰 혹은 테이블의 이름.
SQLtextThe definition of the table. The SQL commands used when creating the table.
테이블의 정의문. 테이블 생성 시 사용된 SQL 명령어들.