├── .gitignore ├── .gitmodules ├── CHANGELOG ├── LICENSE ├── Makefile.in ├── Makefile.tl-parser ├── README.md ├── append.tl ├── auto-static-autocomplete.c ├── auto-static-fetch.c ├── auto-static-print-ds.c ├── auto-static-skip.c ├── auto-static-store.c ├── auto-static.c ├── auto.h ├── binlog.c ├── binlog.tl ├── config.h.in ├── configure ├── configure.ac ├── crypto ├── aes.h ├── aes_altern.c ├── aes_openssl.c ├── bn.h ├── bn_altern.c ├── bn_openssl.c ├── err.h ├── err_altern.c ├── err_openssl.c ├── md5.h ├── md5_altern.c ├── md5_openssl.c ├── meta.h ├── rand.h ├── rand_altern.c ├── rand_openssl.c ├── rsa_pem.h ├── rsa_pem_altern.c ├── rsa_pem_openssl.c ├── sha.h ├── sha_altern.c └── sha_openssl.c ├── encrypted_scheme.tl ├── errors ├── event-old.h ├── gen_constants_h.awk ├── generate.c ├── generate.h ├── m4_ax_check_openssl.m4 ├── m4_ax_check_zlib.m4 ├── mime-types.c ├── mime.types ├── mtproto-client.c ├── mtproto-client.h ├── mtproto-common.c ├── mtproto-common.h ├── mtproto-key.c ├── mtproto-key.h ├── mtproto-utils.c ├── mtproto-utils.h ├── mtproto.tl ├── no-preview.h ├── queries-encrypted.c ├── queries.c ├── queries.h ├── scheme.tl ├── structures.c ├── tg-mime-types.c ├── tg-mime-types.h ├── tgl-binlog.h ├── tgl-fetch.h ├── tgl-inner.h ├── tgl-layout.h ├── tgl-methods-in.h ├── tgl-net-inner.h ├── tgl-net.c ├── tgl-net.h ├── tgl-queries.h ├── tgl-structures.h ├── tgl-timers.c ├── tgl-timers.h ├── tgl.c ├── tgl.h ├── tools.c ├── tools.h ├── tree.h ├── updates.c └── updates.h /.gitignore: -------------------------------------------------------------------------------- 1 | Makefile 2 | autom4te.cache 3 | config.h 4 | config.log 5 | config.status 6 | .idea/ 7 | nbproject/ 8 | bin/ 9 | objs/ 10 | dep/ 11 | auto/ 12 | libs/ 13 | -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "tl-parser"] 2 | path = tl-parser 3 | url = https://github.com/vysheng/tl-parser 4 | -------------------------------------------------------------------------------- /CHANGELOG: -------------------------------------------------------------------------------- 1 | 2.0.3 2 | * updated to layer 31 (bot support) 3 | * changed signature of contact_search method 4 | 2.0.2 5 | * fixed small bugs 6 | * added block/unblock user method 7 | 2.0.1 8 | * store error code for last operation in TLS->error/TLS->error_code 9 | * make interface more consitent 10 | * deleted outdated *_ex functions 11 | * fixed bugs 12 | * support for layer 28: 13 | * support for new pts system 14 | * support for new read system 15 | * support for passwords 16 | * support replies 17 | * support photo captions 18 | * support group links 19 | 1.2.1 20 | * fixed registration/login problem 21 | * added extension to downloads 22 | 1.2.0 23 | * layer 22 support 24 | -------------------------------------------------------------------------------- /Makefile.in: -------------------------------------------------------------------------------- 1 | srcdir=@srcdir@ 2 | 3 | CFLAGS=@CFLAGS@ 4 | LDFLAGS=@LDFLAGS@ @OPENSSL_LDFLAGS@ 5 | CPPFLAGS=@CPPFLAGS@ @OPENSSL_INCLUDES@ 6 | DEFS=@DEFS@ 7 | COMPILE_FLAGS=${CFLAGS} ${CPFLAGS} ${CPPFLAGS} ${DEFS} -Wall -Wextra -Werror -Wno-deprecated-declarations -fno-strict-aliasing -fno-omit-frame-pointer -ggdb -Wno-unused-parameter -fPIC 8 | 9 | EXTRA_LIBS=@LIBS@ @EXTRA_LIBS@ @OPENSSL_LIBS@ 10 | LOCAL_LDFLAGS=-rdynamic -ggdb ${EXTRA_LIBS} 11 | LINK_FLAGS=${LDFLAGS} ${LOCAL_LDFLAGS} 12 | 13 | DEP=dep 14 | AUTO=auto 15 | OBJ=objs 16 | LIB=libs 17 | EXE=bin 18 | DIR_LIST=${DEP} ${DEP}/crypto ${AUTO} ${EXE} ${OBJ} ${OBJ}/crypto ${LIB} ${DEP}/auto ${OBJ}/auto 19 | 20 | LIB_LIST=${LIB}/libtgl.a ${LIB}/libtgl.so 21 | 22 | TGL_OBJECTS=${OBJ}/mtproto-common.o ${OBJ}/mtproto-client.o ${OBJ}/mtproto-key.o ${OBJ}/queries.o ${OBJ}/structures.o ${OBJ}/binlog.o ${OBJ}/tgl.o ${OBJ}/updates.o ${OBJ}/tg-mime-types.o ${OBJ}/mtproto-utils.o ${OBJ}/crypto/bn_openssl.o ${OBJ}/crypto/bn_altern.o ${OBJ}/crypto/rsa_pem_openssl.o ${OBJ}/crypto/rsa_pem_altern.o ${OBJ}/crypto/md5_openssl.o ${OBJ}/crypto/md5_altern.o ${OBJ}/crypto/sha_openssl.o ${OBJ}/crypto/sha_altern.o ${OBJ}/crypto/aes_openssl.o ${OBJ}/crypto/aes_altern.o @EXTRA_OBJECTS@ 23 | TGL_OBJECTS_AUTO=${OBJ}/auto/auto-skip.o ${OBJ}/auto/auto-fetch.o ${OBJ}/auto/auto-store.o ${OBJ}/auto/auto-autocomplete.o ${OBJ}/auto/auto-types.o ${OBJ}/auto/auto-fetch-ds.o ${OBJ}/auto/auto-free-ds.o ${OBJ}/auto/auto-store-ds.o ${OBJ}/auto/auto-print-ds.o 24 | TLD_OBJECTS=${OBJ}/dump-tl-file.o 25 | GENERATE_OBJECTS=${OBJ}/generate.o 26 | COMMON_OBJECTS=${OBJ}/tools.o ${OBJ}/crypto/rand_openssl.o ${OBJ}/crypto/rand_altern.o ${OBJ}/crypto/err_openssl.o ${OBJ}/crypto/err_altern.o 27 | OBJ_C=${GENERATE_OBJECTS} ${COMMON_OBJECTS} ${TGL_OBJECTS} ${TLD_OBJECTS} 28 | 29 | DEPENDENCE=$(subst ${OBJ}/,${DEP}/,$(patsubst %.o,%.d,${OBJ_C})) 30 | DEPENDENCE_LIST=${DEPENDENCE} 31 | 32 | INCLUDE=-I. -I${srcdir} 33 | CC=@CC@ 34 | 35 | .SUFFIXES: 36 | 37 | .SUFFIXES: .c .h .o 38 | 39 | all: ${LIB_LIST} 40 | create_dirs_and_headers: ${DIR_LIST} ${AUTO}/auto-skip.h ${AUTO}/auto-fetch.h ${AUTO}/auto-store.h ${AUTO}/auto-autocomplete.h ${AUTO}/auto-types.h 41 | create_dirs: ${DIR_LIST} 42 | dump-tl: ${EXE}/dump-tl-file 43 | 44 | include ${srcdir}/Makefile.tl-parser 45 | 46 | ${DIR_LIST}: 47 | @test -d $@ || mkdir -p $@ 48 | 49 | -include ${DEPENDENCE_LIST} 50 | 51 | ${TGL_OBJECTS}: ${AUTO}/constants.h ${AUTO}/auto-skip.h ${AUTO}/auto-fetch.h ${AUTO}/auto-store.h ${AUTO}/auto-autocomplete.h ${AUTO}/auto-types.h ${AUTO}/auto-fetch-ds.h ${AUTO}/auto-free-ds.h ${AUTO}/auto-store-ds.h ${AUTO}/auto-print-ds.h 52 | 53 | ${OBJ_C}: ${OBJ}/%.o: ${srcdir}/%.c | create_dirs 54 | ${CC} ${INCLUDE} ${COMPILE_FLAGS} -c -MP -MD -MF ${DEP}/$*.d -MQ ${OBJ}/$*.o -o $@ $< 55 | 56 | ${TGL_OBJECTS_AUTO}: ${OBJ}/auto/%.o: ${AUTO}/%.c | create_dirs 57 | ${CC} ${INCLUDE} ${COMPILE_FLAGS} -iquote ${srcdir}/tgl -c -MP -MD -MF ${DEP}/$*.d -MQ ${OBJ}/$*.o -o $@ $< 58 | 59 | ${LIB}/libtgl.a: ${TGL_OBJECTS} ${COMMON_OBJECTS} ${TGL_OBJECTS_AUTO} 60 | rm -f $@ && ar ruv $@ $^ 61 | 62 | ${LIB}/libtgl.so: ${TGL_OBJECTS} ${COMMON_OBJECTS} ${TGL_OBJECTS_AUTO} 63 | ${CC} -shared -o $@ $^ ${LINK_FLAGS} 64 | 65 | ${EXE}/generate: ${GENERATE_OBJECTS} ${COMMON_OBJECTS} 66 | ${CC} ${GENERATE_OBJECTS} ${COMMON_OBJECTS} ${LINK_FLAGS} -o $@ 67 | 68 | ${AUTO}/scheme.tlo: ${AUTO}/scheme.tl ${EXE}/tl-parser 69 | ${EXE}/tl-parser -e $@ ${AUTO}/scheme.tl 70 | 71 | ${AUTO}/scheme.tl: ${srcdir}/scheme.tl ${srcdir}/encrypted_scheme.tl ${srcdir}/binlog.tl ${srcdir}/mtproto.tl ${srcdir}/append.tl | ${AUTO} 72 | cat $^ > $@ 73 | 74 | ${AUTO}/scheme2.tl: ${AUTO}/scheme.tl ${EXE}/tl-parser 75 | ${EXE}/tl-parser -E ${AUTO}/scheme.tl 2> $@ || ( cat $@ && rm $@ && false ) 76 | 77 | ${AUTO}/auto.c: ${AUTO}/scheme.tlo ${EXE}/generate 78 | ${EXE}/generate ${AUTO}/scheme.tlo > $@ 79 | 80 | ${AUTO}/auto-%.c: ${AUTO}/scheme.tlo ${EXE}/generate auto/constants.h ${AUTO}/auto-%.h | create_dirs_and_headers 81 | ${EXE}/generate -g $(patsubst ${AUTO}/auto-%.c,%,$@) ${AUTO}/scheme.tlo > $@ || ( rm $@ && false ) 82 | 83 | ${AUTO}/auto-%.h: ${AUTO}/scheme.tlo ${EXE}/generate 84 | ${EXE}/generate -g $(patsubst ${AUTO}/auto-%.h,%-header,$@) ${AUTO}/scheme.tlo > $@ || ( rm $@ && false ) 85 | 86 | 87 | ${AUTO}/constants.h: ${AUTO}/scheme2.tl ${srcdir}/gen_constants_h.awk 88 | awk -f ${srcdir}/gen_constants_h.awk < $< > $@ 89 | 90 | ${EXE}/dump-tl-file: ${OBJ}/auto/auto.o ${TLD_OBJECTS} 91 | ${CC} ${OBJ}/auto/auto.o ${TLD_OBJECTS} ${LINK_FLAGS} -o $@ 92 | 93 | clean: 94 | rm -rf ${DIR_LIST} 95 | 96 | distclean: 97 | rm -rf ${DIR_LIST} config.h config.log config.status 98 | 99 | mime-types.c: mime.types 100 | @echo "// DO NOT EDIT! SEE MAKE-TARGET 'gen-mime-types'" > mime-types.c 101 | # xxd is usually packaged with vim-common 102 | xxd -i mime.types >> mime-types.c 103 | -------------------------------------------------------------------------------- /Makefile.tl-parser: -------------------------------------------------------------------------------- 1 | TL_PARSER_OBJECTS=${OBJ}/tl-parser.o ${OBJ}/tlc.o 2 | 3 | ${TL_PARSER_OBJECTS}: ${OBJ}/%.o: ${srcdir}/tl-parser/%.c | create_dirs 4 | ${CC} ${INCLUDE} ${COMPILE_FLAGS} -iquote ${srcdir}/tl-parser -c -MP -MD -MF ${DEP}/$*.d -MQ ${OBJ}/$*.o -o $@ $< 5 | 6 | ${EXE}/tl-parser: ${TL_PARSER_OBJECTS} 7 | ${CC} $^ ${LINK_FLAGS} -o $@ 8 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | This is library that handles telegram api and protocol. 2 | 3 | Current versions: 4 | 5 | - scheme.tl: Layer 38 6 | - encrypted_scheme.tl: Layer 23 7 | 8 | ### API, Protocol documentation 9 | 10 | Documentation for Telegram API is available here: https://core.telegram.org/api 11 | 12 | Documentation for MTproto protocol is available here: https://core.telegram.org/mtproto 13 | 14 | ### Installation 15 | 16 | Clone GitHub Repository 17 | 18 | git clone --recursive https://github.com/vysheng/tgl.git && cd tgl 19 | 20 | #### Linux and BSDs 21 | 22 | Install libs: openssl, zlib 23 | if you want to use provided net/timers then install libevent and add --enable-libevent key to configure 24 | 25 | You can also avoid the OpenSSL dependency: Install gcrypt (>= 1.60, Debian derivates know it as "libgcrypt20-dev"), and add --disable-openssl key to configure 26 | 27 | Then, 28 | 29 | ./configure 30 | make 31 | 32 | ### Contacts 33 | If you would like to ask a question, you can write to my telegram or to the github (or both). To contact me via telegram, you should use import_card method with argument 000653bf:0738ca5d:5521fbac:29246815:a27d0cda 34 | 35 | -------------------------------------------------------------------------------- /append.tl: -------------------------------------------------------------------------------- 1 | ---types--- 2 | decryptedMessageMediaVideoL12#4cee6ef3 str_thumb:bytes thumb_w:int thumb_h:int duration:int w:int h:int size:int key:bytes iv:bytes = DecryptedMessageMedia; 3 | decryptedMessageMediaAudioL12#6080758f duration:int size:int key:bytes iv:bytes = DecryptedMessageMedia; 4 | 5 | updateMsgUpdate id:int pts:int pts_count:int = Update; 6 | 7 | messageMediaPhotoL27#c8c45a2a photo:Photo = MessageMedia; 8 | messageMediaVideoL27#a2d24290 video:Video = MessageMedia; 9 | //messageMediaDocumentL27#2fda2204 document:Document = MessageMedia; 10 | //messageMediaAudioL27#c6b68300 audio:Audio = MessageMedia; 11 | ---functions--- 12 | -------------------------------------------------------------------------------- /auto-static-autocomplete.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #include "config.h" 4 | 5 | #define IN_AUTOCOMPLETE_H 6 | #include "auto-static-store.c" 7 | #undef IN_AUTOCOMPLETE_H 8 | 9 | static int autocomplete_mode; 10 | static char *autocomplete_string; 11 | static int (*autocomplete_fun)(const char *, int, int, char **); 12 | 13 | static void set_autocomplete_string (const char *s) { 14 | if (autocomplete_string) { free (autocomplete_string); } 15 | autocomplete_string = strdup (s); 16 | assert (autocomplete_string); 17 | autocomplete_mode = 1; 18 | } 19 | 20 | static void set_autocomplete_type (int (*f)(const char *, int, int, char **)) { 21 | autocomplete_fun = f; 22 | autocomplete_mode = 2; 23 | } 24 | 25 | #define MAX_FVARS 100 26 | static struct paramed_type *fvars[MAX_FVARS]; 27 | static int fvars_pos; 28 | 29 | static void add_var_to_be_freed (struct paramed_type *P) { 30 | assert (fvars_pos < MAX_FVARS); 31 | fvars[fvars_pos ++] = P; 32 | } 33 | 34 | static void free_vars_to_be_freed (void) { 35 | int i; 36 | for (i = 0; i < fvars_pos; i++) { 37 | tgl_paramed_type_free (fvars[i]); 38 | } 39 | fvars_pos = 0; 40 | } 41 | 42 | int tglf_extf_autocomplete (struct tgl_state *TLS, const char *text, int text_len, int index, char **R, char *data, int data_len) { 43 | #ifdef DISABLE_EXTF 44 | (void) free_vars_to_be_freed; 45 | assert (0); 46 | #else 47 | if (index == -1) { 48 | buffer_pos = data; 49 | buffer_end = data + data_len; 50 | autocomplete_mode = 0; 51 | local_next_token (); 52 | struct paramed_type *P = autocomplete_function_any (); 53 | free_vars_to_be_freed (); 54 | if (P) { tgl_paramed_type_free (P); } 55 | } 56 | if (autocomplete_mode == 0) { return -1; } 57 | int len = strlen (text); 58 | if (autocomplete_mode == 1) { 59 | if (index >= 0) { return -1; } 60 | index = 0; 61 | if (!strncmp (text, autocomplete_string, len)) { 62 | *R = strdup (autocomplete_string); 63 | assert (*R); 64 | return index; 65 | } else { 66 | return -1; 67 | } 68 | } else { 69 | return autocomplete_fun (text, len, index, R); 70 | } 71 | #endif 72 | } 73 | -------------------------------------------------------------------------------- /auto-static-fetch.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #include "config.h" 4 | 5 | static int multiline_output = 1; 6 | static int multiline_offset; 7 | static int multiline_offset_size = 2; 8 | 9 | static int disable_field_names; 10 | 11 | #define OUT_BUF_SIZE (1 << 25) 12 | static char out_buf[OUT_BUF_SIZE]; 13 | static int out_buf_pos; 14 | 15 | #define eprintf(...) \ 16 | do { \ 17 | out_buf_pos += snprintf (out_buf + out_buf_pos, OUT_BUF_SIZE - out_buf_pos, __VA_ARGS__);\ 18 | assert (out_buf_pos < OUT_BUF_SIZE);\ 19 | } while (0)\ 20 | 21 | static int valid_utf8_char (const char *str) { 22 | unsigned char c = (unsigned char) *str; 23 | int n = 0; 24 | 25 | if ((c & 0x80) == 0x00) { 26 | n = 0; 27 | } else if ((c & 0xe0) == 0xc0) { 28 | n = 1; 29 | } else if ((c & 0xf0) == 0xe0) { 30 | n = 2; 31 | } else if ((c & 0xf8) == 0xf0) { 32 | n = 3; 33 | } else if ((c & 0xfc) == 0xf8) { 34 | n = 4; 35 | } else if ((c & 0xfe) == 0xfc) { 36 | n = 5; 37 | } else { 38 | return -1; 39 | } 40 | 41 | int i; 42 | for (i = 0; i < n; i ++) { 43 | if ((((unsigned char)(str[i + 1])) & 0xc0) != 0x80) { 44 | return -1; 45 | } 46 | } 47 | return n + 1; 48 | } 49 | 50 | static void print_escaped_string (const char *str, int len) { 51 | eprintf ("\""); 52 | const char *end = str + len; 53 | while (str < end) { 54 | int n = valid_utf8_char (str); 55 | if (n < 0) { 56 | eprintf ("\\x%02x", (int)(unsigned char)*str); 57 | str ++; 58 | } else if (n >= 2) { 59 | int i; 60 | for (i = 0; i < n; i++) { 61 | eprintf ("%c", *(str ++)); 62 | } 63 | } else if (((unsigned char)*str) >= ' ' && *str != '"' && *str != '\\') { 64 | eprintf ("%c", *str); 65 | str ++; 66 | } else { 67 | switch (*str) { 68 | case '\n': 69 | eprintf("\\n"); 70 | break; 71 | case '\r': 72 | eprintf("\\r"); 73 | break; 74 | case '\t': 75 | eprintf("\\t"); 76 | break; 77 | case '\b': 78 | eprintf("\\b"); 79 | break; 80 | case '\a': 81 | eprintf("\\a"); 82 | break; 83 | case '\\': 84 | eprintf ("\\\\"); 85 | break; 86 | case '"': 87 | eprintf ("\\\""); 88 | break; 89 | default: 90 | eprintf ("\\x%02x", (int)(unsigned char)*str); 91 | break; 92 | } 93 | str ++; 94 | } 95 | } 96 | eprintf ("\""); 97 | } 98 | 99 | static void print_offset (void) { 100 | int i; 101 | for (i = 0; i < multiline_offset; i++) { 102 | eprintf (" "); 103 | } 104 | } 105 | 106 | char *tglf_extf_fetch (struct tgl_state *TLS, struct paramed_type *T) { 107 | #ifdef DISABLE_EXTF 108 | assert (0); 109 | #else 110 | out_buf_pos = 0; 111 | if (fetch_type_any (T) < 0) { return 0; } 112 | return out_buf; 113 | #endif 114 | } 115 | -------------------------------------------------------------------------------- /auto-static-print-ds.c: -------------------------------------------------------------------------------- 1 | #include "config.h" 2 | #ifdef DISABLE_EXTF 3 | #error "EXTF disabled, so nothing uses auto-print anymore." 4 | #endif 5 | 6 | static int multiline_output = 1; 7 | static int multiline_offset; 8 | static int multiline_offset_size = 2; 9 | 10 | static int disable_field_names; 11 | 12 | #define OUT_BUF_SIZE (1 << 25) 13 | static char out_buf[OUT_BUF_SIZE]; 14 | static int out_buf_pos; 15 | 16 | #define eprintf(...) \ 17 | do { \ 18 | out_buf_pos += snprintf (out_buf + out_buf_pos, OUT_BUF_SIZE - out_buf_pos, __VA_ARGS__);\ 19 | assert (out_buf_pos < OUT_BUF_SIZE);\ 20 | } while (0)\ 21 | 22 | static int valid_utf8_char (const char *str) { 23 | unsigned char c = (unsigned char) *str; 24 | int n = 0; 25 | 26 | if ((c & 0x80) == 0x00) { 27 | n = 0; 28 | } else if ((c & 0xe0) == 0xc0) { 29 | n = 1; 30 | } else if ((c & 0xf0) == 0xe0) { 31 | n = 2; 32 | } else if ((c & 0xf8) == 0xf0) { 33 | n = 3; 34 | } else if ((c & 0xfc) == 0xf8) { 35 | n = 4; 36 | } else if ((c & 0xfe) == 0xfc) { 37 | n = 5; 38 | } else { 39 | return -1; 40 | } 41 | 42 | int i; 43 | for (i = 0; i < n; i ++) { 44 | if ((((unsigned char)(str[i + 1])) & 0xc0) != 0x80) { 45 | return -1; 46 | } 47 | } 48 | return n + 1; 49 | } 50 | 51 | static void print_escaped_string (const char *str, int len) { 52 | eprintf ("\""); 53 | const char *end = str + len; 54 | while (str < end) { 55 | int n = valid_utf8_char (str); 56 | if (n < 0) { 57 | eprintf ("\\x%02x", (int)(unsigned char)*str); 58 | str ++; 59 | } else if (n >= 2) { 60 | int i; 61 | for (i = 0; i < n; i++) { 62 | eprintf ("%c", *(str ++)); 63 | } 64 | } else if (((unsigned char)*str) >= ' ' && *str != '"' && *str != '\\') { 65 | eprintf ("%c", *str); 66 | str ++; 67 | } else { 68 | switch (*str) { 69 | case '\n': 70 | eprintf("\\n"); 71 | break; 72 | case '\r': 73 | eprintf("\\r"); 74 | break; 75 | case '\t': 76 | eprintf("\\t"); 77 | break; 78 | case '\b': 79 | eprintf("\\b"); 80 | break; 81 | case '\a': 82 | eprintf("\\a"); 83 | break; 84 | case '\\': 85 | eprintf ("\\\\"); 86 | break; 87 | case '"': 88 | eprintf ("\\\""); 89 | break; 90 | default: 91 | eprintf ("\\x%02x", (int)(unsigned char)*str); 92 | break; 93 | } 94 | str ++; 95 | } 96 | } 97 | eprintf ("\""); 98 | } 99 | 100 | static void print_offset (void) { 101 | int i; 102 | for (i = 0; i < multiline_offset; i++) { 103 | eprintf (" "); 104 | } 105 | } 106 | 107 | char *tglf_extf_print_ds (struct tgl_state *TLS, void *DS, struct paramed_type *T) { 108 | out_buf_pos = 0; 109 | if (print_ds_type_any (DS, T) < 0) { return 0; } 110 | return out_buf; 111 | } 112 | -------------------------------------------------------------------------------- /auto-static-skip.c: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/BaseMax/tgl/ffb04caca71de0cddf28cd33a4575922900a59ed/auto-static-skip.c -------------------------------------------------------------------------------- /auto-static-store.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #include "config.h" 4 | 5 | static int cur_token_len; 6 | static char *cur_token; 7 | static int cur_token_real_len; 8 | static int cur_token_quoted; 9 | 10 | #define expect_token(token,len) \ 11 | if (len != cur_token_len || memcmp (cur_token, token, cur_token_len)) { return -1; } \ 12 | local_next_token (); 13 | 14 | #define expect_token_ptr(token,len) \ 15 | if (len != cur_token_len || memcmp (cur_token, token, cur_token_len)) { return 0; } \ 16 | local_next_token (); 17 | 18 | #define expect_token_autocomplete(token,len) \ 19 | if (cur_token_len == -3 && len >= cur_token_real_len && !memcmp (cur_token, token, cur_token_real_len)) { set_autocomplete_string (token); return -1; }\ 20 | if (len != cur_token_len || memcmp (cur_token, token, cur_token_len)) { return -1; } \ 21 | local_next_token (); 22 | 23 | #define expect_token_ptr_autocomplete(token,len) \ 24 | if (cur_token_len == -3 && len >= cur_token_real_len && !memcmp (cur_token, token, cur_token_real_len)) { set_autocomplete_string (token); return 0; }\ 25 | if (len != cur_token_len || memcmp (cur_token, token, cur_token_len)) { return 0; } \ 26 | local_next_token (); 27 | 28 | static int is_int (void) { 29 | if (cur_token_len <= 0) { return 0; } 30 | char c = cur_token[cur_token_len]; 31 | cur_token[cur_token_len] = 0; 32 | char *p = 0; 33 | 34 | if (strtoll (cur_token, &p, 10)) {} 35 | cur_token[cur_token_len] = c; 36 | 37 | return p == cur_token + cur_token_len; 38 | } 39 | 40 | static long long get_int (void) { 41 | if (cur_token_len <= 0) { return 0; } 42 | char c = cur_token[cur_token_len]; 43 | cur_token[cur_token_len] = 0; 44 | char *p = 0; 45 | 46 | long long val = strtoll (cur_token, &p, 0); 47 | cur_token[cur_token_len] = c; 48 | 49 | return val; 50 | } 51 | 52 | static int is_double (void) { 53 | if (cur_token_len <= 0) { return 0; } 54 | char c = cur_token[cur_token_len]; 55 | cur_token[cur_token_len] = 0; 56 | char *p = 0; 57 | 58 | if (strtod (cur_token, &p)) {} 59 | cur_token[cur_token_len] = c; 60 | 61 | return p == cur_token + cur_token_len; 62 | } 63 | 64 | #ifndef IN_AUTOCOMPLETE_H 65 | static double get_double (void) { 66 | if (cur_token_len <= 0) { return 0; } 67 | char c = cur_token[cur_token_len]; 68 | cur_token[cur_token_len] = 0; 69 | char *p = 0; 70 | 71 | double val = strtod (cur_token, &p); 72 | cur_token[cur_token_len] = c; 73 | 74 | return val; 75 | } 76 | #endif 77 | 78 | static char *buffer_pos, *buffer_end; 79 | 80 | static int is_wspc (char c) { 81 | return c <= 32 && c > 0; 82 | } 83 | 84 | static void skip_wspc (void) { 85 | while (buffer_pos < buffer_end && is_wspc (*buffer_pos)) { 86 | buffer_pos ++; 87 | } 88 | } 89 | 90 | static int is_letter (char c) { 91 | return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '.' || c == '_' || c == '-'; 92 | } 93 | 94 | 95 | static char exp_buffer[1 << 25];; 96 | static int exp_buffer_pos; 97 | 98 | static inline int is_hex (char c) { 99 | return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f'); 100 | } 101 | 102 | static inline int hex2dec (char c) { 103 | if (c >= '0' && c <= '9') { return c - '0'; } 104 | else { return c - 'a' + 10; } 105 | } 106 | 107 | static void expand_backslashed (char *s, int len) { 108 | int backslashed = 0; 109 | exp_buffer_pos = 0; 110 | int i = 0; 111 | while (i < len) { 112 | assert (i + 3 <= (1 << 25)); 113 | if (backslashed) { 114 | backslashed = 0; 115 | switch (s[i ++]) { 116 | case 'n': 117 | exp_buffer[exp_buffer_pos ++] = '\n'; 118 | break; 119 | case 'r': 120 | exp_buffer[exp_buffer_pos ++] = '\r'; 121 | break; 122 | case 't': 123 | exp_buffer[exp_buffer_pos ++] = '\t'; 124 | break; 125 | case 'b': 126 | exp_buffer[exp_buffer_pos ++] = '\b'; 127 | break; 128 | case 'a': 129 | exp_buffer[exp_buffer_pos ++] = '\a'; 130 | break; 131 | case '\\': 132 | exp_buffer[exp_buffer_pos ++] = '\\'; 133 | break; 134 | case 'x': 135 | if (i + 2 > len || !is_hex (s[i]) || !is_hex (s[i + 1])) { 136 | exp_buffer_pos = -1; 137 | return; 138 | } 139 | exp_buffer[exp_buffer_pos ++] = hex2dec (s[i]) * 16 + hex2dec (s[i + 1]); 140 | i += 2; 141 | break; 142 | default: 143 | break; 144 | } 145 | } else { 146 | if (s[i] == '\\') { 147 | backslashed = 1; 148 | i ++; 149 | } else { 150 | exp_buffer[exp_buffer_pos ++] = s[i ++]; 151 | } 152 | } 153 | } 154 | } 155 | 156 | static void local_next_token (void) { 157 | skip_wspc (); 158 | cur_token_quoted = 0; 159 | if (buffer_pos >= buffer_end) { 160 | cur_token_len = -3; 161 | cur_token_real_len = 0; 162 | return; 163 | } 164 | char c = *buffer_pos; 165 | if (is_letter (c)) { 166 | cur_token = buffer_pos; 167 | while (buffer_pos < buffer_end && is_letter (*buffer_pos)) { 168 | buffer_pos ++; 169 | } 170 | if (buffer_pos < buffer_end) { 171 | cur_token_len = buffer_pos - cur_token; 172 | } else { 173 | cur_token_real_len = buffer_pos - cur_token; 174 | cur_token_len = -3; 175 | } 176 | return; 177 | } else if (c == '"') { 178 | cur_token_quoted = 1; 179 | cur_token = buffer_pos ++; 180 | int backslashed = 0; 181 | while (buffer_pos < buffer_end && (*buffer_pos != '"' || backslashed)) { 182 | if (*buffer_pos == '\\') { 183 | backslashed ^= 1; 184 | } else { 185 | backslashed = 0; 186 | } 187 | buffer_pos ++; 188 | } 189 | if (*buffer_pos == '"') { 190 | buffer_pos ++; 191 | expand_backslashed (cur_token + 1, buffer_pos - cur_token - 2); 192 | if (exp_buffer_pos < 0) { 193 | cur_token_len = -2; 194 | } else { 195 | cur_token_len = exp_buffer_pos; 196 | cur_token = exp_buffer; 197 | } 198 | } else { 199 | cur_token_len = -2; 200 | } 201 | return; 202 | } else { 203 | if (c) { 204 | cur_token = buffer_pos ++; 205 | cur_token_len = 1; 206 | } else { 207 | cur_token_len = -3; 208 | cur_token_real_len = 0; 209 | } 210 | } 211 | } 212 | 213 | static struct paramed_type *paramed_type_dup (struct paramed_type *P) { 214 | if (ODDP (P)) { return P; } 215 | struct paramed_type *R = malloc (sizeof (*R)); 216 | assert (R); 217 | R->type = malloc (sizeof (*R->type)); 218 | assert (R->type); 219 | memcpy (R->type, P->type, sizeof (*P->type)); 220 | R->type->id = strdup (P->type->id); 221 | assert (R->type->id); 222 | 223 | if (P->type->params_num) { 224 | R->params = malloc (sizeof (void *) * P->type->params_num); 225 | assert (R->params); 226 | int i; 227 | for (i = 0; i < P->type->params_num; i++) { 228 | R->params[i] = paramed_type_dup (P->params[i]); 229 | } 230 | } 231 | return R; 232 | } 233 | 234 | #ifndef IN_AUTOCOMPLETE_H 235 | void tgl_paramed_type_free (struct paramed_type *P) { 236 | if (ODDP (P)) { return; } 237 | if (P->type->params_num) { 238 | int i; 239 | for (i = 0; i < P->type->params_num; i++) { 240 | tgl_paramed_type_free (P->params[i]); 241 | } 242 | free (P->params); 243 | } 244 | free (P->type->id); 245 | free (P->type); 246 | free (P); 247 | } 248 | #else 249 | void tgl_paramed_type_free (struct paramed_type *P); 250 | #endif 251 | 252 | #ifndef IN_AUTOCOMPLETE_H 253 | struct paramed_type *tglf_extf_store (struct tgl_state *TLS, const char *data, int data_len) { 254 | #ifdef DISABLE_EXTF 255 | assert (0); 256 | #else 257 | buffer_pos = (char *)data; 258 | buffer_end = (char *)(data + data_len); 259 | local_next_token (); 260 | return store_function_any (); 261 | #endif 262 | } 263 | 264 | int tglf_store_type (struct tgl_state *TLS, const char *data, int data_len, struct paramed_type *P) { 265 | buffer_pos = (char *)data; 266 | buffer_end = (char *)(data + data_len); 267 | local_next_token (); 268 | return store_type_any (P); 269 | } 270 | #endif 271 | -------------------------------------------------------------------------------- /auto-static.c: -------------------------------------------------------------------------------- 1 | /* 2 | This file is part of tgl-library 3 | 4 | This library is free software; you can redistribute it and/or 5 | modify it under the terms of the GNU Lesser General Public 6 | License as published by the Free Software Foundation; either 7 | version 2.1 of the License, or (at your option) any later version. 8 | 9 | This library is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 | Lesser General Public License for more details. 13 | 14 | You should have received a copy of the GNU Lesser General Public 15 | License along with this library; if not, write to the Free Software 16 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 17 | 18 | Copyright Vitaly Valtman 2014-2015 19 | */ 20 | 21 | #include "mtproto-common.h" 22 | #include "config.h" 23 | #include 24 | 25 | #ifndef DISABLE_EXTF 26 | static int cur_token_len; 27 | static char *cur_token; 28 | static int cur_token_real_len; 29 | static int cur_token_quoted; 30 | 31 | #define expect_token(token,len) \ 32 | if (len != cur_token_len || memcmp (cur_token, token, cur_token_len)) { return -1; } \ 33 | local_next_token (); 34 | 35 | #define expect_token_ptr(token,len) \ 36 | if (len != cur_token_len || memcmp (cur_token, token, cur_token_len)) { return 0; } \ 37 | local_next_token (); 38 | 39 | #define expect_token_autocomplete(token,len) \ 40 | if (cur_token_len == -3 && len >= cur_token_real_len && !memcmp (cur_token, token, cur_token_real_len)) { set_autocomplete_string (token); return -1; }\ 41 | if (len != cur_token_len || memcmp (cur_token, token, cur_token_len)) { return -1; } \ 42 | local_next_token (); 43 | 44 | #define expect_token_ptr_autocomplete(token,len) \ 45 | if (cur_token_len == -3 && len >= cur_token_real_len && !memcmp (cur_token, token, cur_token_real_len)) { set_autocomplete_string (token); return 0; }\ 46 | if (len != cur_token_len || memcmp (cur_token, token, cur_token_len)) { return 0; } \ 47 | local_next_token (); 48 | 49 | 50 | static int autocomplete_mode; 51 | static char *autocomplete_string; 52 | static int (*autocomplete_fun)(const char *, int, int, char **); 53 | 54 | static void set_autocomplete_string (const char *s) { 55 | if (autocomplete_string) { free (autocomplete_string); } 56 | autocomplete_string = strdup (s); 57 | assert (autocomplete_string); 58 | autocomplete_mode = 1; 59 | } 60 | 61 | static void set_autocomplete_type (int (*f)(const char *, int, int, char **)) { 62 | autocomplete_fun = f; 63 | autocomplete_mode = 2; 64 | } 65 | 66 | static int is_int (void) { 67 | if (cur_token_len <= 0) { return 0; } 68 | char c = cur_token[cur_token_len]; 69 | cur_token[cur_token_len] = 0; 70 | char *p = 0; 71 | 72 | if (strtoll (cur_token, &p, 10)) {} 73 | cur_token[cur_token_len] = c; 74 | 75 | return p == cur_token + cur_token_len; 76 | } 77 | 78 | static long long get_int (void) { 79 | if (cur_token_len <= 0) { return 0; } 80 | char c = cur_token[cur_token_len]; 81 | cur_token[cur_token_len] = 0; 82 | char *p = 0; 83 | 84 | long long val = strtoll (cur_token, &p, 0); 85 | cur_token[cur_token_len] = c; 86 | 87 | return val; 88 | } 89 | 90 | static int is_double (void) { 91 | if (cur_token_len <= 0) { return 0; } 92 | char c = cur_token[cur_token_len]; 93 | cur_token[cur_token_len] = 0; 94 | char *p = 0; 95 | 96 | if (strtod (cur_token, &p)) {} 97 | cur_token[cur_token_len] = c; 98 | 99 | return p == cur_token + cur_token_len; 100 | } 101 | 102 | static double get_double (void) { 103 | if (cur_token_len <= 0) { return 0; } 104 | char c = cur_token[cur_token_len]; 105 | cur_token[cur_token_len] = 0; 106 | char *p = 0; 107 | 108 | double val = strtod (cur_token, &p); 109 | cur_token[cur_token_len] = c; 110 | 111 | return val; 112 | } 113 | 114 | static struct paramed_type *paramed_type_dup (struct paramed_type *P) { 115 | if (ODDP (P)) { return P; } 116 | struct paramed_type *R = malloc (sizeof (*R)); 117 | assert (R); 118 | R->type = malloc (sizeof (*R->type)); 119 | assert (R->type); 120 | memcpy (R->type, P->type, sizeof (*P->type)); 121 | R->type->id = strdup (P->type->id); 122 | assert (R->type->id); 123 | 124 | if (P->type->params_num) { 125 | R->params = malloc (sizeof (void *) * P->type->params_num); 126 | assert (R->params); 127 | int i; 128 | for (i = 0; i < P->type->params_num; i++) { 129 | R->params[i] = paramed_type_dup (P->params[i]); 130 | } 131 | } 132 | return R; 133 | } 134 | 135 | void tgl_paramed_type_free (struct paramed_type *P) { 136 | if (ODDP (P)) { return; } 137 | if (P->type->params_num) { 138 | int i; 139 | for (i = 0; i < P->type->params_num; i++) { 140 | tgl_paramed_type_free (P->params[i]); 141 | } 142 | free (P->params); 143 | } 144 | free (P->type->id); 145 | free (P->type); 146 | free (P); 147 | } 148 | 149 | static char *buffer_pos, *buffer_end; 150 | 151 | static int is_wspc (char c) { 152 | return c <= 32 && c > 0; 153 | } 154 | 155 | static void skip_wspc (void) { 156 | while (buffer_pos < buffer_end && is_wspc (*buffer_pos)) { 157 | buffer_pos ++; 158 | } 159 | } 160 | 161 | static int is_letter (char c) { 162 | return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '.' || c == '_' || c == '-'; 163 | } 164 | 165 | 166 | static char exp_buffer[1 << 25];; 167 | static int exp_buffer_pos; 168 | 169 | static inline int is_hex (char c) { 170 | return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f'); 171 | } 172 | 173 | static inline int hex2dec (char c) { 174 | if (c >= '0' && c <= '9') { return c - '0'; } 175 | else { return c - 'a' + 10; } 176 | } 177 | 178 | static void expand_backslashed (char *s, int len) { 179 | int backslashed = 0; 180 | exp_buffer_pos = 0; 181 | int i = 0; 182 | while (i < len) { 183 | assert (i + 3 <= (1 << 25)); 184 | if (backslashed) { 185 | backslashed = 0; 186 | switch (s[i ++]) { 187 | case 'n': 188 | exp_buffer[exp_buffer_pos ++] = '\n'; 189 | break; 190 | case 'r': 191 | exp_buffer[exp_buffer_pos ++] = '\r'; 192 | break; 193 | case 't': 194 | exp_buffer[exp_buffer_pos ++] = '\t'; 195 | break; 196 | case 'b': 197 | exp_buffer[exp_buffer_pos ++] = '\b'; 198 | break; 199 | case 'a': 200 | exp_buffer[exp_buffer_pos ++] = '\a'; 201 | break; 202 | case '\\': 203 | exp_buffer[exp_buffer_pos ++] = '\\'; 204 | break; 205 | case 'x': 206 | if (i + 2 > len || !is_hex (s[i]) || !is_hex (s[i + 1])) { 207 | exp_buffer_pos = -1; 208 | return; 209 | } 210 | exp_buffer[exp_buffer_pos ++] = hex2dec (s[i]) * 16 + hex2dec (s[i + 1]); 211 | i += 2; 212 | break; 213 | default: 214 | break; 215 | } 216 | } else { 217 | if (s[i] == '\\') { 218 | backslashed = 1; 219 | i ++; 220 | } else { 221 | exp_buffer[exp_buffer_pos ++] = s[i ++]; 222 | } 223 | } 224 | } 225 | } 226 | 227 | static void local_next_token (void) { 228 | skip_wspc (); 229 | cur_token_quoted = 0; 230 | if (buffer_pos >= buffer_end) { 231 | cur_token_len = -3; 232 | cur_token_real_len = 0; 233 | return; 234 | } 235 | char c = *buffer_pos; 236 | if (is_letter (c)) { 237 | cur_token = buffer_pos; 238 | while (buffer_pos < buffer_end && is_letter (*buffer_pos)) { 239 | buffer_pos ++; 240 | } 241 | if (buffer_pos < buffer_end) { 242 | cur_token_len = buffer_pos - cur_token; 243 | } else { 244 | cur_token_real_len = buffer_pos - cur_token; 245 | cur_token_len = -3; 246 | } 247 | return; 248 | } else if (c == '"') { 249 | cur_token_quoted = 1; 250 | cur_token = buffer_pos ++; 251 | int backslashed = 0; 252 | while (buffer_pos < buffer_end && (*buffer_pos != '"' || backslashed)) { 253 | if (*buffer_pos == '\\') { 254 | backslashed ^= 1; 255 | } else { 256 | backslashed = 0; 257 | } 258 | buffer_pos ++; 259 | } 260 | if (*buffer_pos == '"') { 261 | buffer_pos ++; 262 | expand_backslashed (cur_token + 1, buffer_pos - cur_token - 2); 263 | if (exp_buffer_pos < 0) { 264 | cur_token_len = -2; 265 | } else { 266 | cur_token_len = exp_buffer_pos; 267 | cur_token = exp_buffer; 268 | } 269 | } else { 270 | cur_token_len = -2; 271 | } 272 | return; 273 | } else { 274 | if (c) { 275 | cur_token = buffer_pos ++; 276 | cur_token_len = 1; 277 | } else { 278 | cur_token_len = -3; 279 | cur_token_real_len = 0; 280 | } 281 | } 282 | } 283 | 284 | #define MAX_FVARS 100 285 | static struct paramed_type *fvars[MAX_FVARS]; 286 | static int fvars_pos; 287 | 288 | static void add_var_to_be_freed (struct paramed_type *P) { 289 | assert (fvars_pos < MAX_FVARS); 290 | fvars[fvars_pos ++] = P; 291 | } 292 | 293 | static void free_vars_to_be_freed (void) { 294 | int i; 295 | for (i = 0; i < fvars_pos; i++) { 296 | tgl_paramed_type_free (fvars[i]); 297 | } 298 | fvars_pos = 0; 299 | } 300 | 301 | int tglf_extf_autocomplete (struct tgl_state *TLS, const char *text, int text_len, int index, char **R, char *data, int data_len) { 302 | if (index == -1) { 303 | buffer_pos = data; 304 | buffer_end = data + data_len; 305 | autocomplete_mode = 0; 306 | local_next_token (); 307 | struct paramed_type *P = autocomplete_function_any (); 308 | free_vars_to_be_freed (); 309 | if (P) { tgl_paramed_type_free (P); } 310 | } 311 | if (autocomplete_mode == 0) { return -1; } 312 | int len = strlen (text); 313 | if (autocomplete_mode == 1) { 314 | if (index >= 0) { return -1; } 315 | index = 0; 316 | if (!strncmp (text, autocomplete_string, len)) { 317 | *R = strdup (autocomplete_string); 318 | assert (*R); 319 | return index; 320 | } else { 321 | return -1; 322 | } 323 | } else { 324 | return autocomplete_fun (text, len, index, R); 325 | } 326 | } 327 | 328 | #endif 329 | -------------------------------------------------------------------------------- /auto.h: -------------------------------------------------------------------------------- 1 | /* 2 | This file is part of tgl-library 3 | 4 | This library is free software; you can redistribute it and/or 5 | modify it under the terms of the GNU Lesser General Public 6 | License as published by the Free Software Foundation; either 7 | version 2.1 of the License, or (at your option) any later version. 8 | 9 | This library is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 | Lesser General Public License for more details. 13 | 14 | You should have received a copy of the GNU Lesser General Public 15 | License along with this library; if not, write to the Free Software 16 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 17 | 18 | Copyright Vitaly Valtman 2014-2015 19 | */ 20 | #ifndef __AUTO_H__ 21 | #define __AUTO_H__ 22 | 23 | #include "tools.h" 24 | 25 | struct tl_type_descr { 26 | unsigned name; 27 | char *id; 28 | int params_num; 29 | long long params_types; 30 | }; 31 | 32 | struct paramed_type { 33 | struct tl_type_descr *type; 34 | struct paramed_type **params; 35 | }; 36 | 37 | #define NAME_ARRAY 0x89932ad9 38 | 39 | #define TYPE_TO_PARAM(NAME) (&(struct paramed_type) {.type = &tl_type_## NAME, .params=0}) 40 | #define TYPE_TO_PARAM_1(NAME,PARAM1) (&(struct paramed_type) {.type = &tl_type_## NAME, .params=(struct paramed_type *[1]){PARAM1}}) 41 | #define ODDP(x) (((long)(x)) & 1) 42 | #define EVENP(x) (!ODDP(x)) 43 | #define INT2PTR(x) (void *)(long)(((long)x) * 2 + 1) 44 | #define PTR2INT(x) ((((long)x) - 1) / 2) 45 | 46 | static inline void *memdup (const void *d, int len) { 47 | assert (d || !len); 48 | if (!d) { return NULL; } 49 | void *r = talloc (len); 50 | memcpy (r, d, len); 51 | return r; 52 | } 53 | 54 | #define DS_LVAL(x) ((x) ? *(x) : 0) 55 | #define DS_STR(x) ((x) ? (x)->data : NULL), ((x) ? (x)->len : 0) 56 | #define DS_RSTR(x) ((x) ? (x)->len : 0), ((x) ? (x)->data : NULL) 57 | #define DS_STR_DUP(x) memdup(((x) ? (x)->data : NULL), ((x) ? (x)->len + 1: 0)) 58 | #define DS_BVAL(x) ((x) && ((x)->magic == CODE_bool_true)) 59 | 60 | void tgl_paramed_type_free (struct paramed_type *P); 61 | 62 | #endif 63 | -------------------------------------------------------------------------------- /binlog.tl: -------------------------------------------------------------------------------- 1 | ---types--- 2 | 3 | binlog.encrKey key:64*[int] = binlog.EncrKey; 4 | 5 | binlog.peerUser = binlog.PeerType; 6 | binlog.peerChat = binlog.PeerType; 7 | binlog.peerChannel = binlog.PeerType; 8 | 9 | binlog.peer peer_type:binlog.PeerType peer_id:int = binlog.Peer; 10 | 11 | 12 | binlog.start = binlog.Update; 13 | 14 | binlog.authKey dc:int key:%binlog.EncrKey = binlog.Update; 15 | binlog.defaultDc dc:int = binlog.Update; 16 | binlog.dcSigned dc:int = binlog.Update; 17 | 18 | binlog.dcOption flags:int dc:int name:string ip:string port:int = binlog.Update; 19 | 20 | binlog.ourId id:int = binlog.Update; 21 | 22 | binlog.setDhParams root:int prime:%binlog.EncrKey version:int = binlog.Update; 23 | 24 | 25 | 26 | binlog.setPts pts:int = binlog.Update; 27 | binlog.setQts qts:int = binlog.Update; 28 | binlog.setDate date:int = binlog.Update; 29 | binlog.setSeq seq:int = binlog.Update; 30 | 31 | binlog.peerDelete peer:%binlog.Peer = binlog.Update; 32 | 33 | binlog.encrChat#84977251 flags:# id:int 34 | access_hash:flags.17?long 35 | date:flags.18?int 36 | admin:flags.19?int 37 | user_id:flags.20?int 38 | key:flags.21?%binlog.EncrKey 39 | g_key:flags.22?%binlog.EncrKey 40 | state:flags.23?int 41 | ttl:flags.24?int 42 | layer:flags.25?int 43 | in_seq_no:flags.26?int last_in_seq_no:flags.26?int out_seq_no:flags.26?int 44 | key_fingerprint:flags.27?long 45 | = binlog.Update; 46 | 47 | binlog.encrChatExchange#9d49488d flags:# id:int 48 | exchange_id:flags.17?long 49 | key:flags.18?%binlog.EncrKey 50 | state:flags.19?int 51 | = binlog.Update; 52 | 53 | binlog.user#127cf2f9 flags:# id:int 54 | access_hash:flags.17?long 55 | first_name:flags.18?string last_name:flags.18?string 56 | phone:flags.19?string 57 | username:flags.20?string 58 | photo:flags.21?Photo 59 | real_first_name:flags.22?string real_last_name:flags.22?string 60 | user_photo:flags.23?UserProfilePhoto 61 | last_read_in:flags.24?int 62 | last_read_out:flags.25?int 63 | bot_info:flags.26?BotInfo 64 | = binlog.Update; 65 | 66 | binlog.chat#0a10aa92 flags:# id:int 67 | title:flags.17?string 68 | user_num:flags.18?int 69 | date:flags.19?int 70 | version:flags.20?int participants:flags.20?(Vector ChatParticipant) 71 | chat_photo:flags.21?ChatPhoto 72 | photo:flags.22?Photo 73 | admin:flags.23?int 74 | last_read_in:flags.24?int 75 | last_read_out:flags.25?int 76 | = binlog.Update; 77 | 78 | binlog.channel flags:# id:int 79 | title:flags.17?string 80 | username:flags.18?string 81 | date:flags.19?int 82 | version:flags.20?int 83 | chat_photo:flags.21?ChatPhoto 84 | photo:flags.22?Photo 85 | about:flags.23?int 86 | last_read_in:flags.24?int 87 | admins_count:flags.25?int 88 | kicked_count:flags.26?int 89 | access_hash:flags.27?long 90 | = binlog.Update; 91 | 92 | 93 | binlog.chatAddParticipant id:int version:int user_id:int inviter_id:int date:int = binlog.Update; 94 | binlog.chatDelParticipant id:int version:int user_id:int = binlog.Update; 95 | 96 | binlog.setMsgId old_id:long new_id:int = binlog.Update; 97 | binlog.messageDelete lid:long = binlog.Update; 98 | 99 | binlog.messageNew#427cfcdb flags:# lid:long 100 | from:flags.17?%binlog.Peer to:flags.17?%binlog.Peer 101 | fwd_from_id:flags.18?%binlog.Peer fwd_date:flags.18?int 102 | date:flags.19?int 103 | message:flags.20?string 104 | media:flags.21?MessageMedia 105 | action:flags.22?MessageAction 106 | reply_id:flags.23?int 107 | reply_markup:flags.24?ReplyMarkup 108 | = binlog.Update; 109 | 110 | binlog.messageEncrNew#6cf7cabc flags:# lid:long 111 | from:flags.17?%binlog.Peer to:flags.17?%binlog.Peer 112 | //empty 18 bit 113 | date:flags.19?int 114 | message:flags.20?string 115 | encr_media:flags.21?DecryptedMessageMedia 116 | encr_action:flags.22?DecryptedMessageAction 117 | file:flags.23?EncryptedFile 118 | = binlog.Update; 119 | 120 | binlog.msgUpdate#6dd4d85f lid:long = binlog.Update; 121 | 122 | binlog.resetAuthorization = binlog.Update; 123 | 124 | 125 | ---functions--- 126 | -------------------------------------------------------------------------------- /config.h.in: -------------------------------------------------------------------------------- 1 | /* config.h.in. Generated from configure.ac by autoheader. */ 2 | 3 | /* disable extf queries */ 4 | #undef DISABLE_EXTF 5 | 6 | /* Use libevent v1 */ 7 | #undef EVENT_V1 8 | 9 | /* Use libevent v2 */ 10 | #undef EVENT_V2 11 | 12 | /* Define to 1 if you have the `alarm' function. */ 13 | #undef HAVE_ALARM 14 | 15 | /* Define to 1 if you have the header file. */ 16 | #undef HAVE_ARPA_INET_H 17 | 18 | /* Define to 1 if you have the `endpwent' function. */ 19 | #undef HAVE_ENDPWENT 20 | 21 | /* Define to 1 if you have the header file. */ 22 | #undef HAVE_EXECINFO_H 23 | 24 | /* Define to 1 if you have the header file. */ 25 | #undef HAVE_FCNTL_H 26 | 27 | /* Define to 1 if you have the header file. */ 28 | #undef HAVE_INTTYPES_H 29 | 30 | /* Define to 1 if you have the `event' library (-levent). */ 31 | #undef HAVE_LIBEVENT 32 | 33 | /* Define to 1 if you have the `gcrypt' library (-lgcrypt). */ 34 | #undef HAVE_LIBGCRYPT 35 | 36 | /* Define to 1 if you have `z' library (-lz) */ 37 | #undef HAVE_LIBZ 38 | 39 | /* Define to 1 if you have the header file. */ 40 | #undef HAVE_MACH_MACH_H 41 | 42 | /* Define to 1 if your system has a GNU libc compatible `malloc' function, and 43 | to 0 otherwise. */ 44 | #undef HAVE_MALLOC 45 | 46 | /* Define to 1 if you have the header file. */ 47 | #undef HAVE_MALLOC_H 48 | 49 | /* Define to 1 if you have the `memmove' function. */ 50 | #undef HAVE_MEMMOVE 51 | 52 | /* Define to 1 if you have the header file. */ 53 | #undef HAVE_MEMORY_H 54 | 55 | /* Define to 1 if you have the `memset' function. */ 56 | #undef HAVE_MEMSET 57 | 58 | /* Define to 1 if you have the `mkdir' function. */ 59 | #undef HAVE_MKDIR 60 | 61 | /* Define to 1 if you have the header file. */ 62 | #undef HAVE_NETDB_H 63 | 64 | /* Define to 1 if you have the header file. */ 65 | #undef HAVE_NETINET_IN_H 66 | 67 | /* Define to 1 if your system has a GNU libc compatible `realloc' function, 68 | and to 0 otherwise. */ 69 | #undef HAVE_REALLOC 70 | 71 | /* Define to 1 if you have the `select' function. */ 72 | #undef HAVE_SELECT 73 | 74 | /* Define to 1 if you have the `socket' function. */ 75 | #undef HAVE_SOCKET 76 | 77 | /* Define to 1 if you have the header file. */ 78 | #undef HAVE_STDINT_H 79 | 80 | /* Define to 1 if you have the header file. */ 81 | #undef HAVE_STDLIB_H 82 | 83 | /* Define to 1 if you have the `strdup' function. */ 84 | #undef HAVE_STRDUP 85 | 86 | /* Define to 1 if you have the header file. */ 87 | #undef HAVE_STRINGS_H 88 | 89 | /* Define to 1 if you have the header file. */ 90 | #undef HAVE_STRING_H 91 | 92 | /* Define to 1 if you have the `strndup' function. */ 93 | #undef HAVE_STRNDUP 94 | 95 | /* Define to 1 if you have the header file. */ 96 | #undef HAVE_SYS_FILE_H 97 | 98 | /* Define to 1 if you have the header file. */ 99 | #undef HAVE_SYS_SOCKET_H 100 | 101 | /* Define to 1 if you have the header file. */ 102 | #undef HAVE_SYS_STAT_H 103 | 104 | /* Define to 1 if you have the header file. */ 105 | #undef HAVE_SYS_TYPES_H 106 | 107 | /* Define to 1 if you have the header file. */ 108 | #undef HAVE_TERMIOS_H 109 | 110 | /* Define to 1 if you have the `uname' function. */ 111 | #undef HAVE_UNAME 112 | 113 | /* Define to 1 if you have the header file. */ 114 | #undef HAVE_UNISTD_H 115 | 116 | /* Define to 1 if the system has the `__builtin_bswap32' built-in function */ 117 | #undef HAVE___BUILTIN_BSWAP32 118 | 119 | /* Define to the address where bug reports for this package should be sent. */ 120 | #undef PACKAGE_BUGREPORT 121 | 122 | /* Define to the full name of this package. */ 123 | #undef PACKAGE_NAME 124 | 125 | /* Define to the full name and version of this package. */ 126 | #undef PACKAGE_STRING 127 | 128 | /* Define to the one symbol short name of this package. */ 129 | #undef PACKAGE_TARNAME 130 | 131 | /* Define to the home page for this package. */ 132 | #undef PACKAGE_URL 133 | 134 | /* Define to the version of this package. */ 135 | #undef PACKAGE_VERSION 136 | 137 | /* Define to 1 if you have the ANSI C header files. */ 138 | #undef STDC_HEADERS 139 | 140 | /* avoid OpenSSL entirely, use libgcrypt instead (this can't read *.pub files, 141 | though.) */ 142 | #undef TGL_AVOID_OPENSSL 143 | 144 | /* fixed for correct valgrind work */ 145 | #undef VALGRIND_FIXES 146 | 147 | /* Define to `int' if doesn't define. */ 148 | #undef gid_t 149 | 150 | /* Define to `__inline__' or `__inline' if that's what the C compiler 151 | calls it, or to nothing if 'inline' is not supported under any name. */ 152 | #ifndef __cplusplus 153 | #undef inline 154 | #endif 155 | 156 | /* Define to rpl_malloc if the replacement function should be used. */ 157 | #undef malloc 158 | 159 | /* Define to rpl_realloc if the replacement function should be used. */ 160 | #undef realloc 161 | 162 | /* Define to `unsigned int' if does not define. */ 163 | #undef size_t 164 | 165 | /* Define to `int' if doesn't define. */ 166 | #undef uid_t 167 | -------------------------------------------------------------------------------- /configure.ac: -------------------------------------------------------------------------------- 1 | AC_PREREQ([2.68]) 2 | AC_INIT([telegram-cli], [1.0]) 3 | AC_CONFIG_SRCDIR([config.h.in]) 4 | AC_CONFIG_HEADERS([config.h]) 5 | 6 | m4_include([m4_ax_check_openssl.m4]) 7 | m4_include([m4_ax_check_zlib.m4]) 8 | 9 | # Checks for programs. 10 | AC_PROG_CC 11 | 12 | # BSD locations for headers and libraries from packages, Linux locations for self-compiled stuff. 13 | CPPFLAGS="$CPPFLAGS -I/usr/local/include" 14 | LDFLAGS="$LDFLAGS -L/usr/local/lib" 15 | 16 | # Checks for libraries. 17 | AC_SEARCH_LIBS([clock_gettime], [rt]) 18 | 19 | EVENT_VER="" 20 | EXTRA_OBJECTS="" 21 | 22 | # OPENSSL_INCLUDES to the include directives required 23 | # OPENSSL_LIBS to the -l directives required 24 | # OPENSSL_LDFLAGS to the -L or -R flags required 25 | 26 | AC_ARG_ENABLE(openssl,[ --disable-openssl disables OpenSSL, and don't link against it 27 | (this can't read *.pub files, though.)], 28 | [ 29 | if test "x$enableval" = "xno" ; then 30 | AC_DEFINE([TGL_AVOID_OPENSSL],[1],[avoid OpenSSL entirely, use libgcrypt instead (this can't read *.pub files, though.)]) 31 | AC_CHECK_LIB([gcrypt], [gcry_mpi_snatch], [], [AC_MSG_ERROR(["Need libgcrypt >= 1.60"])]) 32 | else 33 | # Don't be annoying, so don't inform the user about --disable-openssl 34 | AX_CHECK_OPENSSL(,[AC_MSG_ERROR([No openssl found.])]) 35 | fi 36 | ],[ 37 | AX_CHECK_OPENSSL(,[AC_MSG_ERROR([No openssl found. With --disable-openssl, libtgl will use libgcrypt instead.])]) 38 | ]) 39 | 40 | AX_CHECK_ZLIB(, [AC_MSG_ERROR([No zlib found])]) 41 | 42 | AC_ARG_ENABLE(extf,[ --enable-extf enables extended queries system], 43 | [ 44 | if test "x$enableval" = "xno" ; then 45 | AC_DEFINE([DISABLE_EXTF],[1],[disable extf queries]) 46 | fi 47 | ],[ 48 | ]) 49 | 50 | AC_ARG_ENABLE(libevent,[ --enable-libevent include libevent-based net and timers], 51 | [ 52 | if test "x$enableval" = "xyes" ; then 53 | AC_CHECK_LIB([event], [event_base_new], [], [AC_MSG_ERROR([no libevent found])]) 54 | AC_CHECK_HEADER(event2/event.h, [AC_DEFINE([EVENT_V2], [1], [Use libevent v2])], [ 55 | AC_CHECK_HEADER(event.h, [AC_DEFINE([EVENT_V1], [1], [Use libevent v1])], [AC_MSG_ERROR([no libevent found])]) 56 | ]) 57 | EXTRA_OBJECTS="${EXTRA_OBJECTS} objs/tgl-net.o objs/tgl-timers.o" 58 | fi 59 | ],[ 60 | ]) 61 | 62 | AC_ARG_ENABLE(valgrind,[ --enable-valgrind fixes for correct valgrind work], 63 | [ 64 | if test "x$enableval" = "xyes" ; then 65 | AC_CHECK_HEADER(valgrind/memcheck.h, [AC_DEFINE([VALGRIND_FIXES], [1], [fixed for correct valgrind work])], [ 66 | ]) 67 | fi 68 | ],[ 69 | ]) 70 | 71 | # Checks for header files. 72 | AC_CHECK_HEADERS([fcntl.h malloc.h netdb.h stdlib.h string.h unistd.h arpa/inet.h mach/mach.h netinet/in.h sys/file.h sys/socket.h termios.h]) 73 | 74 | # FreeBSD needs -lexecinfo 75 | AC_CHECK_HEADERS([execinfo.h], [tgl_found_execinfo_header=yes; break;]) 76 | AS_IF([test "x$tgl_found_execinfo_header" = "xyes"], 77 | [AC_SEARCH_LIBS([backtrace_symbols_fd], [execinfo])]) 78 | 79 | 80 | # Checks for typedefs, structures, and compiler characteristics. 81 | AC_TYPE_SIZE_T 82 | AC_TYPE_UID_T 83 | AC_C_INLINE 84 | 85 | # Checks for library functions. 86 | AC_FUNC_MALLOC 87 | AC_FUNC_REALLOC 88 | AC_CHECK_FUNCS([alarm endpwent memset memmove mkdir select socket strdup strndup uname]) 89 | 90 | AC_SUBST(EXTRA_LIBS) 91 | AC_SUBST(EXTRA_OBJECTS) 92 | AC_CONFIG_FILES([Makefile]) 93 | AC_OUTPUT 94 | 95 | -------------------------------------------------------------------------------- /crypto/aes.h: -------------------------------------------------------------------------------- 1 | /* 2 | This file is part of tgl-library 3 | 4 | This library is free software; you can redistribute it and/or 5 | modify it under the terms of the GNU Lesser General Public 6 | License as published by the Free Software Foundation; either 7 | version 2.1 of the License, or (at your option) any later version. 8 | 9 | This library is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 | Lesser General Public License for more details. 13 | 14 | You should have received a copy of the GNU Lesser General Public 15 | License along with this library; if not, write to the Free Software 16 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 17 | 18 | Copyright Ben Wiederhake 2015 19 | */ 20 | 21 | #ifndef __TGL_CRYPTO_AES_H__ 22 | #define __TGL_CRYPTO_AES_H__ 23 | 24 | #include /* size_t */ 25 | 26 | #include "../config.h" 27 | 28 | typedef struct TGLC_aes_key { 29 | char _dummy[ 30 | #ifdef TGL_AVOID_OPENSSL 31 | 32 32 | #else 33 | 244 34 | #endif 35 | ]; 36 | } TGLC_aes_key; 37 | 38 | void TGLC_aes_set_encrypt_key (const unsigned char *userKey, const int bits, TGLC_aes_key *key); 39 | void TGLC_aes_set_decrypt_key (const unsigned char *userKey, const int bits, TGLC_aes_key *key); 40 | void TGLC_aes_ige_encrypt (const unsigned char *in, unsigned char *out, size_t length, const TGLC_aes_key *key, unsigned char *ivec, const int enc); 41 | 42 | #endif 43 | -------------------------------------------------------------------------------- /crypto/aes_altern.c: -------------------------------------------------------------------------------- 1 | /* 2 | This file is part of tgl-library 3 | 4 | This library is free software; you can redistribute it and/or 5 | modify it under the terms of the GNU Lesser General Public 6 | License as published by the Free Software Foundation; either 7 | version 2.1 of the License, or (at your option) any later version. 8 | 9 | This library is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 | Lesser General Public License for more details. 13 | 14 | You should have received a copy of the GNU Lesser General Public 15 | License along with this library; if not, write to the Free Software 16 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 17 | 18 | Copyright Ben Wiederhake 2015 19 | */ 20 | 21 | #include "../config.h" 22 | 23 | #ifdef TGL_AVOID_OPENSSL 24 | 25 | /* Marginally speed up compilation */ 26 | #define GCRYPT_NO_MPI_MACROS 27 | /* Fail-fast when something becomes deprecated. */ 28 | #define GCRYPT_NO_DEPRECATED 29 | 30 | #include 31 | #include 32 | 33 | #include "aes.h" 34 | #include "meta.h" 35 | #include "rand.h" 36 | 37 | #define AES_BLOCK_BITS 128 38 | #define AES_BLOCK_BYTES (AES_BLOCK_BITS/8) 39 | #define AES_KEY_BITS 256 40 | #define AES_KEY_BYTES (AES_KEY_BITS/8) 41 | 42 | typedef char check_struct_sizes[(sizeof (TGLC_aes_key) == AES_KEY_BYTES) - 1]; 43 | 44 | void TGLC_aes_set_encrypt_key (const unsigned char *userKey, const int bits, TGLC_aes_key *key) { 45 | assert (bits == AES_KEY_BITS); 46 | memcpy (key->_dummy, userKey, AES_KEY_BYTES); 47 | } 48 | 49 | void TGLC_aes_set_decrypt_key (const unsigned char *userKey, const int bits, TGLC_aes_key *key) { 50 | TGLC_aes_set_encrypt_key (userKey, bits, key); 51 | } 52 | 53 | // TODO: Try to use gcrypt's internal buf_xor? 54 | static void do_xor_block (const unsigned char *in, const unsigned char *with, unsigned char *out) { 55 | /* TODO: Referencing them as "size_t" (or whatever biggest numerical type available) is probably faster, but also more error-prone. */ 56 | int i; 57 | for (i = 0; i < 16; ++i) { 58 | *out++ = *in++ ^ *with++; 59 | } 60 | } 61 | 62 | static gcry_error_t do_ige_encrypt (const unsigned char *in, unsigned char *out, 63 | unsigned long n_blocks, gcry_cipher_hd_t cipher, unsigned char *ivec) { 64 | /* The docs say, at the end of section 2: 65 | * "OpenSSL uses the convention that the first block of the IV is x_0 66 | * and the second block is y_0." 67 | * Well, no. This is a subtle error: FIRST comes the previous ENcrypted block, 68 | * THEN the DEcrypted block. 69 | * Also, keep a copy of the old cleartext, in case in == out. */ 70 | unsigned char buf[2 * 16]; 71 | unsigned char *prev_x = buf; 72 | unsigned char *cur_x = buf + 16; 73 | memcpy (prev_x, ivec + 16, 16); 74 | const unsigned char *prev_y = ivec; 75 | 76 | /* gcrypt doesn't allow overlapping buffers. Kudos to "reubensammut" for 77 | * noticing this. Note that this also works if in == out. */ 78 | unsigned char tmp[16]; 79 | unsigned long i; 80 | for (i = 0; i < n_blocks; ++i) { 81 | memcpy (cur_x, in, 16); 82 | /* Might overwrite 'in'. */ 83 | do_xor_block (in, prev_y, out); 84 | gcry_error_t gcry_error = gcry_cipher_encrypt (cipher, tmp, 16, out, 16); 85 | if (gcry_error) { 86 | return gcry_error; 87 | } 88 | do_xor_block (tmp, prev_x, out); 89 | prev_y = out; // encrypted is in 'out' 90 | in += 16; 91 | out += 16; 92 | // swap (tmp_x, cur_x); 93 | unsigned char *tmp_x = cur_x; 94 | cur_x = prev_x; 95 | prev_x = tmp_x; 96 | } 97 | if (n_blocks > 0) { 98 | /* OpenSSL updates the IV, so we do that, too. 99 | * One could avoid memcpy here, as it's only 16 bytes. */ 100 | memcpy (ivec + 16, prev_x, 16); 101 | memcpy (ivec, prev_y, 16); 102 | } 103 | return 0; 104 | } 105 | 106 | static gcry_error_t do_ige_decrypt (const unsigned char *in, unsigned char *out, 107 | unsigned long n_blocks, gcry_cipher_hd_t cipher, unsigned char *ivec) { 108 | /* Also, keep a copy of the old ciphertext, in case in == out. */ 109 | unsigned char buf[2 * 16]; 110 | unsigned char *prev_y = buf; 111 | unsigned char *cur_y = buf + 16; 112 | memcpy (prev_y, ivec, 16); 113 | const unsigned char *prev_x = ivec + 16; 114 | 115 | /* gcrypt doesn't allow overlapping buffers. Kudos to "reubensammut" for 116 | * noticing this. Note that this also works if in == out. */ 117 | unsigned char tmp[16]; 118 | unsigned long i; 119 | for (i = 0; i < n_blocks; ++i) { 120 | memcpy (cur_y, in, 16); 121 | /* Might overwrite 'in'. */ 122 | do_xor_block (in, prev_x, out); 123 | gcry_error_t gcry_error = gcry_cipher_decrypt (cipher, tmp, 16, out, 16); 124 | if (gcry_error) { 125 | return gcry_error; 126 | } 127 | do_xor_block (tmp, prev_y, out); 128 | prev_x = out; // decrypted is in 'out' 129 | in += 16; 130 | out += 16; 131 | // swap (tmp_y, cur_y); 132 | unsigned char *tmp_y = cur_y; 133 | cur_y = prev_y; 134 | prev_y = tmp_y; 135 | } 136 | /* Do not change ivec */ 137 | return 0; 138 | } 139 | 140 | /* Needs to be given an IV of length 2*AES_BLOCK_BYTES. */ 141 | void TGLC_aes_ige_encrypt (const unsigned char *in, unsigned char *out, size_t length, const TGLC_aes_key *key, unsigned char *ivec, const int enc) { 142 | assert (!(length % AES_BLOCK_BYTES)); 143 | 144 | /* Set it up. */ 145 | gcry_cipher_hd_t cipher; 146 | gcry_error_t gcry_error = gcry_cipher_open (&cipher, GCRY_CIPHER_AES256, GCRY_CIPHER_MODE_ECB, 0); 147 | assert (!gcry_error); 148 | gcry_cipher_setkey (cipher, key->_dummy, AES_KEY_BYTES); 149 | 150 | if (enc) { 151 | gcry_error = do_ige_encrypt(in, out, length / AES_BLOCK_BYTES, cipher, ivec); 152 | } else { 153 | gcry_error = do_ige_decrypt(in, out, length / AES_BLOCK_BYTES, cipher, ivec); 154 | } 155 | assert (!gcry_error); 156 | 157 | gcry_cipher_close(cipher); 158 | } 159 | 160 | #endif 161 | -------------------------------------------------------------------------------- /crypto/aes_openssl.c: -------------------------------------------------------------------------------- 1 | /* 2 | This file is part of tgl-library 3 | 4 | This library is free software; you can redistribute it and/or 5 | modify it under the terms of the GNU Lesser General Public 6 | License as published by the Free Software Foundation; either 7 | version 2.1 of the License, or (at your option) any later version. 8 | 9 | This library is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 | Lesser General Public License for more details. 13 | 14 | You should have received a copy of the GNU Lesser General Public 15 | License along with this library; if not, write to the Free Software 16 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 17 | 18 | Copyright Ben Wiederhake 2015 19 | */ 20 | 21 | #include "../config.h" 22 | 23 | #ifndef TGL_AVOID_OPENSSL 24 | 25 | #include 26 | 27 | #include "aes.h" 28 | #include "meta.h" 29 | 30 | typedef char check_struct_sizes[(sizeof (AES_KEY) == sizeof (TGLC_aes_key)) - 1]; 31 | 32 | TGLC_WRAPPER_ASSOC(aes_key,AES_KEY) 33 | 34 | void TGLC_aes_set_encrypt_key (const unsigned char *userKey, const int bits, TGLC_aes_key *key) { 35 | int success = AES_set_encrypt_key(userKey, bits, unwrap_aes_key (key)); 36 | assert (0 == success); 37 | } 38 | 39 | void TGLC_aes_set_decrypt_key (const unsigned char *userKey, const int bits, TGLC_aes_key *key) { 40 | int success = AES_set_decrypt_key(userKey, bits, unwrap_aes_key (key)); 41 | assert (0 == success); 42 | } 43 | 44 | void TGLC_aes_ige_encrypt (const unsigned char *in, unsigned char *out, size_t length, const TGLC_aes_key *key, unsigned char *ivec, const int enc) { 45 | AES_ige_encrypt (in, out, length, unwrap_aes_key (key), ivec, enc); 46 | } 47 | 48 | #endif 49 | -------------------------------------------------------------------------------- /crypto/bn.h: -------------------------------------------------------------------------------- 1 | /* 2 | This file is part of tgl-library 3 | 4 | This library is free software; you can redistribute it and/or 5 | modify it under the terms of the GNU Lesser General Public 6 | License as published by the Free Software Foundation; either 7 | version 2.1 of the License, or (at your option) any later version. 8 | 9 | This library is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 | Lesser General Public License for more details. 13 | 14 | You should have received a copy of the GNU Lesser General Public 15 | License along with this library; if not, write to the Free Software 16 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 17 | 18 | Copyright Ben Wiederhake 2015 19 | */ 20 | 21 | #ifndef __TGL_CRYPTO_BN_H__ 22 | #define __TGL_CRYPTO_BN_H__ 23 | 24 | typedef struct TGLC_bn_ctx TGLC_bn_ctx; 25 | typedef struct TGLC_bn TGLC_bn; 26 | 27 | TGLC_bn_ctx *TGLC_bn_ctx_new (void); 28 | void TGLC_bn_ctx_free (TGLC_bn_ctx* ctx); 29 | 30 | TGLC_bn *TGLC_bn_new (void); 31 | void TGLC_bn_free (TGLC_bn *a); 32 | void TGLC_bn_clear_free (TGLC_bn *a); 33 | int TGLC_bn_cmp (const TGLC_bn *a, const TGLC_bn *b); 34 | int TGLC_bn_is_prime (const TGLC_bn *a, int checks, void (*callback) (int, int, void *), TGLC_bn_ctx *ctx, void *cb_arg); 35 | int TGLC_bn_bn2bin (const TGLC_bn *a, unsigned char *to); 36 | TGLC_bn * TGLC_bn_bin2bn(const unsigned char *s, int len, TGLC_bn *ret); 37 | int TGLC_bn_set_word (TGLC_bn *a, unsigned long w); 38 | unsigned long TGLC_bn_get_word (const TGLC_bn *a); 39 | int TGLC_bn_num_bits (const TGLC_bn *a); 40 | void TGLC_bn_sub (TGLC_bn *r, const TGLC_bn *a, const TGLC_bn *b); 41 | int TGLC_bn_div (TGLC_bn *dv, TGLC_bn *rem, const TGLC_bn *a, const TGLC_bn *d, TGLC_bn_ctx *ctx); 42 | int TGLC_bn_mod_exp (TGLC_bn *r, const TGLC_bn *a, const TGLC_bn *p, const TGLC_bn *m, TGLC_bn_ctx *ctx); 43 | 44 | #define TGLC_bn_num_bytes(a) ((TGLC_bn_num_bits(a)+7)/8) 45 | #define TGLC_bn_mod(rem,m,d,ctx) TGLC_bn_div(NULL,(rem),(m),(d),(ctx)) 46 | 47 | #endif 48 | -------------------------------------------------------------------------------- /crypto/bn_altern.c: -------------------------------------------------------------------------------- 1 | /* 2 | This file is part of tgl-library 3 | 4 | This library is free software; you can redistribute it and/or 5 | modify it under the terms of the GNU Lesser General Public 6 | License as published by the Free Software Foundation; either 7 | version 2.1 of the License, or (at your option) any later version. 8 | 9 | This library is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 | Lesser General Public License for more details. 13 | 14 | You should have received a copy of the GNU Lesser General Public 15 | License along with this library; if not, write to the Free Software 16 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 17 | 18 | Copyright Ben Wiederhake 2015 19 | */ 20 | 21 | #include "../config.h" 22 | 23 | #ifdef TGL_AVOID_OPENSSL 24 | 25 | /* Fail-fast when something becomes deprecated. */ 26 | #define GCRYPT_NO_DEPRECATED 27 | 28 | #include 29 | #include 30 | 31 | #include "bn.h" 32 | #include "meta.h" 33 | 34 | // There is no "_ctx" equivalent in gcrypt. 35 | TGLC_WRAPPER_ASSOC(bn_ctx,int) 36 | TGLC_WRAPPER_ASSOC(bn,struct gcry_mpi) 37 | 38 | TGLC_bn_ctx *TGLC_bn_ctx_new (void) { 39 | /* Must not be the null pointer, but must never be dereferenced. Assume that "1" is an invalid address. */ 40 | return ((void *)1); 41 | } 42 | 43 | void TGLC_bn_ctx_free (TGLC_bn_ctx* ctx) { 44 | (void) ctx; 45 | } 46 | 47 | TGLC_bn *TGLC_bn_new (void) { 48 | // TODO: Determine how many bits should be pre-allocated. 49 | TGLC_bn *ret = wrap_bn (gcry_mpi_new (2048)); 50 | assert (ret); 51 | return ret; 52 | } 53 | 54 | void TGLC_bn_free (TGLC_bn *a) { 55 | gcry_mpi_release (unwrap_bn (a)); 56 | } 57 | 58 | void TGLC_bn_clear_free (TGLC_bn *a) { 59 | /* This only protects against accidental use-after-free. I don't see the point of clearing, since we're not operating in protected memory AND the most crucial fields are never cleared anyway. */ 60 | gcry_mpi_set_ui (unwrap_bn (a), 0); 61 | gcry_mpi_release (unwrap_bn (a)); 62 | } 63 | 64 | int TGLC_bn_cmp (const TGLC_bn *a, const TGLC_bn *b) { 65 | return gcry_mpi_cmp (unwrap_bn (a), unwrap_bn (b)); 66 | } 67 | 68 | int TGLC_bn_is_prime (const TGLC_bn *a, int checks, void (*callback) (int, int, void *), TGLC_bn_ctx *ctx, void *cb_arg) { 69 | assert (0 == checks); 70 | assert (NULL == callback); 71 | (void) ctx; 72 | assert (NULL == cb_arg); 73 | /* Second argument is ignored. 74 | * No really, here's what libgcrypt's source does: 75 | * (void)flags; */ 76 | gcry_error_t err = gcry_prime_check (unwrap_bn (a), 0); 77 | /* This is nasty. In essence, gcry returns a bool whether it is NOT a prime. */ 78 | return !err; 79 | } 80 | 81 | int TGLC_bn_bn2bin (const TGLC_bn *a, unsigned char *to) { 82 | const unsigned long num_bytes = TGLC_bn_num_bytes (a); 83 | gcry_error_t gcry_error = gcry_mpi_print (GCRYMPI_FMT_USG, to, num_bytes, NULL, unwrap_bn (a)); 84 | assert (!gcry_error); 85 | return num_bytes; 86 | } 87 | 88 | TGLC_bn *TGLC_bn_bin2bn(const unsigned char *s, int len, TGLC_bn *ret) { 89 | gcry_mpi_t ret_ptr = NULL; 90 | gcry_error_t gcry_error = gcry_mpi_scan (&ret_ptr, GCRYMPI_FMT_USG, s, len, NULL); 91 | assert (!gcry_error); 92 | assert (ret_ptr); 93 | 94 | if (!ret) { 95 | return wrap_bn (ret_ptr); 96 | } 97 | 98 | gcry_mpi_snatch (unwrap_bn (ret), ret_ptr); 99 | return ret; 100 | } 101 | 102 | int TGLC_bn_set_word (TGLC_bn *a, unsigned long w) { 103 | assert (a); 104 | gcry_mpi_set_ui (unwrap_bn (a), w); 105 | return 1; 106 | } 107 | 108 | unsigned long TGLC_bn_get_word (const TGLC_bn *a) { 109 | const unsigned long num_bytes = TGLC_bn_num_bytes (a); 110 | assert (sizeof (unsigned long) >= num_bytes); 111 | unsigned char tmp[sizeof (unsigned long)]; 112 | memset (tmp, 0, sizeof (unsigned long)); 113 | TGLC_bn_bn2bin (a, tmp + sizeof (unsigned long) - num_bytes); 114 | 115 | /* Inefficient, but runs a total of three times per connection. */ 116 | /* TODO: Optimize? */ 117 | unsigned long ret = 0; 118 | unsigned int i; 119 | for (i = 0; i < sizeof (unsigned long); ++i) { 120 | ret <<= 8; 121 | ret |= tmp[i]; 122 | } 123 | return ret; 124 | } 125 | 126 | int TGLC_bn_num_bits (const TGLC_bn *a) { 127 | return gcry_mpi_get_nbits (unwrap_bn (a)); 128 | } 129 | 130 | void TGLC_bn_sub (TGLC_bn *r, const TGLC_bn *a, const TGLC_bn *b) { 131 | gcry_mpi_sub (unwrap_bn (r), unwrap_bn (a), unwrap_bn (b)); 132 | } 133 | 134 | int TGLC_bn_div (TGLC_bn *dv, TGLC_bn *rem, const TGLC_bn *a, const TGLC_bn *d, TGLC_bn_ctx *ctx) { 135 | (void) ctx; 136 | gcry_mpi_div (unwrap_bn (dv), unwrap_bn (rem), unwrap_bn (a), unwrap_bn (d), 0); 137 | return 1; 138 | } 139 | 140 | int TGLC_bn_mod_exp (TGLC_bn *r, const TGLC_bn *a, const TGLC_bn *p, const TGLC_bn *m, TGLC_bn_ctx *ctx) { 141 | (void) ctx; 142 | gcry_mpi_powm (unwrap_bn (r), unwrap_bn (a), unwrap_bn (p), unwrap_bn (m)); 143 | return 1; 144 | } 145 | 146 | #endif 147 | -------------------------------------------------------------------------------- /crypto/bn_openssl.c: -------------------------------------------------------------------------------- 1 | /* 2 | This file is part of tgl-library 3 | 4 | This library is free software; you can redistribute it and/or 5 | modify it under the terms of the GNU Lesser General Public 6 | License as published by the Free Software Foundation; either 7 | version 2.1 of the License, or (at your option) any later version. 8 | 9 | This library is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 | Lesser General Public License for more details. 13 | 14 | You should have received a copy of the GNU Lesser General Public 15 | License along with this library; if not, write to the Free Software 16 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 17 | 18 | Copyright Ben Wiederhake 2015 19 | */ 20 | 21 | #include "../config.h" 22 | 23 | #ifndef TGL_AVOID_OPENSSL 24 | 25 | #include 26 | 27 | #include 28 | 29 | #include "bn.h" 30 | #include "meta.h" 31 | 32 | TGLC_WRAPPER_ASSOC(bn_ctx,BN_CTX) 33 | TGLC_WRAPPER_ASSOC(bn,BIGNUM) 34 | 35 | TGLC_bn_ctx *TGLC_bn_ctx_new (void) { 36 | return wrap_bn_ctx (BN_CTX_new ()); 37 | } 38 | 39 | void TGLC_bn_ctx_free (TGLC_bn_ctx* ctx) { 40 | BN_CTX_free (unwrap_bn_ctx (ctx)); 41 | } 42 | 43 | TGLC_bn *TGLC_bn_new (void) { 44 | return wrap_bn (BN_new ()); 45 | } 46 | 47 | void TGLC_bn_free (TGLC_bn *a) { 48 | BN_free (unwrap_bn (a)); 49 | } 50 | 51 | void TGLC_bn_clear_free (TGLC_bn *a) { 52 | BN_clear_free (unwrap_bn (a)); 53 | } 54 | 55 | int TGLC_bn_cmp (const TGLC_bn *a, const TGLC_bn *b) { 56 | return BN_cmp (unwrap_bn (a), unwrap_bn (b)); 57 | } 58 | 59 | int TGLC_bn_is_prime (const TGLC_bn *a, int checks, void (*callback) (int, int, void *), TGLC_bn_ctx *ctx, void *cb_arg) { 60 | return BN_is_prime (unwrap_bn (a), checks, callback, unwrap_bn_ctx (ctx), cb_arg); 61 | } 62 | 63 | int TGLC_bn_bn2bin (const TGLC_bn *a, unsigned char *to) { 64 | return BN_bn2bin (unwrap_bn (a), to); 65 | } 66 | 67 | TGLC_bn * TGLC_bn_bin2bn(const unsigned char *s, int len, TGLC_bn *ret) { 68 | return wrap_bn (BN_bin2bn (s, len, unwrap_bn (ret))); 69 | } 70 | 71 | int TGLC_bn_set_word (TGLC_bn *a, unsigned long w) { 72 | return BN_set_word (unwrap_bn (a), w); 73 | } 74 | 75 | unsigned long TGLC_bn_get_word (const TGLC_bn *a) { 76 | return BN_get_word (unwrap_bn (a)); 77 | } 78 | 79 | int TGLC_bn_num_bits (const TGLC_bn *a) { 80 | return BN_num_bits (unwrap_bn (a)); 81 | } 82 | 83 | void TGLC_bn_sub (TGLC_bn *r, const TGLC_bn *a, const TGLC_bn *b) { 84 | int res = BN_sub (unwrap_bn (r), unwrap_bn (a), unwrap_bn (b)); 85 | assert (res); 86 | } 87 | 88 | int TGLC_bn_div (TGLC_bn *dv, TGLC_bn *rem, const TGLC_bn *a, const TGLC_bn *d, TGLC_bn_ctx *ctx) { 89 | return BN_div (unwrap_bn (dv), unwrap_bn (rem), unwrap_bn (a), unwrap_bn (d), unwrap_bn_ctx (ctx)); 90 | } 91 | 92 | int TGLC_bn_mod_exp (TGLC_bn *r, const TGLC_bn *a, const TGLC_bn *p, const TGLC_bn *m, TGLC_bn_ctx *ctx) { 93 | return BN_mod_exp (unwrap_bn (r), unwrap_bn (a), unwrap_bn (p), unwrap_bn (m), unwrap_bn_ctx (ctx)); 94 | } 95 | 96 | #endif 97 | -------------------------------------------------------------------------------- /crypto/err.h: -------------------------------------------------------------------------------- 1 | /* 2 | This file is part of tgl-library 3 | 4 | This library is free software; you can redistribute it and/or 5 | modify it under the terms of the GNU Lesser General Public 6 | License as published by the Free Software Foundation; either 7 | version 2.1 of the License, or (at your option) any later version. 8 | 9 | This library is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 | Lesser General Public License for more details. 13 | 14 | You should have received a copy of the GNU Lesser General Public 15 | License along with this library; if not, write to the Free Software 16 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 17 | 18 | Copyright Ben Wiederhake 2015 19 | */ 20 | 21 | #ifndef __TGL_CRYPTO_ERR_H__ 22 | #define __TGL_CRYPTO_ERR_H__ 23 | 24 | #include 25 | 26 | void TGLC_err_print_errors_fp (FILE *fp); 27 | 28 | #endif 29 | -------------------------------------------------------------------------------- /crypto/err_altern.c: -------------------------------------------------------------------------------- 1 | /* 2 | This file is part of tgl-library 3 | 4 | This library is free software; you can redistribute it and/or 5 | modify it under the terms of the GNU Lesser General Public 6 | License as published by the Free Software Foundation; either 7 | version 2.1 of the License, or (at your option) any later version. 8 | 9 | This library is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 | Lesser General Public License for more details. 13 | 14 | You should have received a copy of the GNU Lesser General Public 15 | License along with this library; if not, write to the Free Software 16 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 17 | 18 | Copyright Ben Wiederhake 2015 19 | */ 20 | 21 | #include "../config.h" 22 | 23 | #ifdef TGL_AVOID_OPENSSL 24 | 25 | #include 26 | 27 | #include "err.h" 28 | 29 | void TGLC_err_print_errors_fp (FILE *fp) { 30 | // Can't print anything meaningful, so don't. 31 | (void) fp; 32 | } 33 | 34 | #endif 35 | -------------------------------------------------------------------------------- /crypto/err_openssl.c: -------------------------------------------------------------------------------- 1 | /* 2 | This file is part of tgl-library 3 | 4 | This library is free software; you can redistribute it and/or 5 | modify it under the terms of the GNU Lesser General Public 6 | License as published by the Free Software Foundation; either 7 | version 2.1 of the License, or (at your option) any later version. 8 | 9 | This library is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 | Lesser General Public License for more details. 13 | 14 | You should have received a copy of the GNU Lesser General Public 15 | License along with this library; if not, write to the Free Software 16 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 17 | 18 | Copyright Ben Wiederhake 2015 19 | */ 20 | 21 | #include "../config.h" 22 | 23 | #ifndef TGL_AVOID_OPENSSL 24 | 25 | #include 26 | 27 | #include "err.h" 28 | 29 | void TGLC_err_print_errors_fp (FILE *fp) { 30 | ERR_print_errors_fp (fp); 31 | } 32 | 33 | #endif 34 | -------------------------------------------------------------------------------- /crypto/md5.h: -------------------------------------------------------------------------------- 1 | /* 2 | This file is part of tgl-library 3 | 4 | This library is free software; you can redistribute it and/or 5 | modify it under the terms of the GNU Lesser General Public 6 | License as published by the Free Software Foundation; either 7 | version 2.1 of the License, or (at your option) any later version. 8 | 9 | This library is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 | Lesser General Public License for more details. 13 | 14 | You should have received a copy of the GNU Lesser General Public 15 | License along with this library; if not, write to the Free Software 16 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 17 | 18 | Copyright Ben Wiederhake 2015 19 | */ 20 | 21 | #ifndef __TGL_CRYPTO_MD5_H__ 22 | #define __TGL_CRYPTO_MD5_H__ 23 | 24 | #include /* size_t */ 25 | 26 | void TGLC_md5 (const unsigned char *d, size_t n, unsigned char *md); 27 | 28 | #endif 29 | -------------------------------------------------------------------------------- /crypto/md5_altern.c: -------------------------------------------------------------------------------- 1 | /* 2 | This file is part of tgl-library 3 | 4 | This library is free software; you can redistribute it and/or 5 | modify it under the terms of the GNU Lesser General Public 6 | License as published by the Free Software Foundation; either 7 | version 2.1 of the License, or (at your option) any later version. 8 | 9 | This library is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 | Lesser General Public License for more details. 13 | 14 | You should have received a copy of the GNU Lesser General Public 15 | License along with this library; if not, write to the Free Software 16 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 17 | 18 | Copyright Ben Wiederhake 2015 19 | */ 20 | 21 | #include "../config.h" 22 | 23 | #ifdef TGL_AVOID_OPENSSL 24 | 25 | /* Marginally speed up compilation */ 26 | #define GCRYPT_NO_MPI_MACROS 27 | /* Fail-fast when something becomes deprecated. */ 28 | #define GCRYPT_NO_DEPRECATED 29 | 30 | #include 31 | 32 | #include "md5.h" 33 | 34 | void TGLC_md5 (const unsigned char *d, size_t n, unsigned char *md) { 35 | gcry_md_hash_buffer (GCRY_MD_MD5, md, d, n); 36 | } 37 | 38 | #endif 39 | -------------------------------------------------------------------------------- /crypto/md5_openssl.c: -------------------------------------------------------------------------------- 1 | /* 2 | This file is part of tgl-library 3 | 4 | This library is free software; you can redistribute it and/or 5 | modify it under the terms of the GNU Lesser General Public 6 | License as published by the Free Software Foundation; either 7 | version 2.1 of the License, or (at your option) any later version. 8 | 9 | This library is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 | Lesser General Public License for more details. 13 | 14 | You should have received a copy of the GNU Lesser General Public 15 | License along with this library; if not, write to the Free Software 16 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 17 | 18 | Copyright Ben Wiederhake 2015 19 | */ 20 | 21 | #include "../config.h" 22 | 23 | #ifndef TGL_AVOID_OPENSSL 24 | 25 | #include 26 | 27 | #include "md5.h" 28 | 29 | void TGLC_md5(const unsigned char *d, size_t n, unsigned char *md) { 30 | MD5(d, n, md); 31 | } 32 | 33 | #endif 34 | -------------------------------------------------------------------------------- /crypto/meta.h: -------------------------------------------------------------------------------- 1 | /* 2 | This file is part of tgl-library 3 | 4 | This library is free software; you can redistribute it and/or 5 | modify it under the terms of the GNU Lesser General Public 6 | License as published by the Free Software Foundation; either 7 | version 2.1 of the License, or (at your option) any later version. 8 | 9 | This library is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 | Lesser General Public License for more details. 13 | 14 | You should have received a copy of the GNU Lesser General Public 15 | License along with this library; if not, write to the Free Software 16 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 17 | 18 | Copyright Ben Wiederhake 2015 19 | */ 20 | 21 | #ifndef CRYPTO_META_H_ 22 | #define CRYPTO_META_H_ 23 | 24 | #include 25 | 26 | /* All this wrapping/unwrapping solves a fundamental problem: 27 | * - The libtgl implementation wants access to the TGLC_* types. 28 | * - The libtgl implementation should not see any other definitions from any 29 | * external crypto library (to make sure no symbol slips "through" during the 30 | * OpenSSL-to-gcrypt transition). 31 | * - Most TGLC_* types (3 out of 4 types) are exclusively used as pointers 32 | * throughout the libtgl source, in a way to allow for incomplete types. 33 | * - The CORE type (e.g. BIGNUM from ) may be incomplete, 34 | * even for tglc. 35 | * This means the standard approaches don't work: 36 | * - TGLC_NAME can't be a typedef to CORE, since CORE shouldn't even be visible 37 | * from libtgl. 38 | * - TGLC_NAME can't be a pointer to CORE, same reason. Also, it would require 39 | * a significant amount of rewriting (error-prone work). 40 | * - TGLC_NAME can't be a void pointer. Retain type checking! 41 | * - So TGLC_NAME *must* be an incomplete custom struct. 42 | * However, this ensues the following ugliness. 43 | * 44 | * The standard doesn't explicitly allow it, but there's a pretty good argument 45 | * that casting ptr-to-some-struct to ptr-to-other-struct is *probably* okay for 46 | * most compilers: https://stackoverflow.com/a/8702750/3070326 47 | */ 48 | #define TGLC_WRAPPER_ASSOC(NAME,CORE) \ 49 | static TGLC_ ## NAME *wrap_ ## NAME (const CORE *p) \ 50 | __attribute__ ((unused)); \ 51 | static CORE *unwrap_ ## NAME (const TGLC_ ## NAME *p) \ 52 | __attribute__ ((unused)); \ 53 | static CORE *unwrap_ ## NAME (const TGLC_ ## NAME *p) { \ 54 | return (CORE *)p; \ 55 | } \ 56 | static TGLC_ ## NAME *wrap_ ## NAME (const CORE *p) { \ 57 | return (TGLC_ ## NAME *)p; \ 58 | } 59 | 60 | #endif /* CRYPTO_META_H_ */ 61 | -------------------------------------------------------------------------------- /crypto/rand.h: -------------------------------------------------------------------------------- 1 | /* 2 | This file is part of tgl-library 3 | 4 | This library is free software; you can redistribute it and/or 5 | modify it under the terms of the GNU Lesser General Public 6 | License as published by the Free Software Foundation; either 7 | version 2.1 of the License, or (at your option) any later version. 8 | 9 | This library is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 | Lesser General Public License for more details. 13 | 14 | You should have received a copy of the GNU Lesser General Public 15 | License along with this library; if not, write to the Free Software 16 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 17 | 18 | Copyright Ben Wiederhake 2015 19 | */ 20 | 21 | #ifndef __TGL_CRYPTO_RAND_H__ 22 | #define __TGL_CRYPTO_RAND_H__ 23 | 24 | void TGLC_rand_add (const void *buf, int num, double entropy); 25 | int TGLC_rand_bytes (unsigned char *buf, int num); 26 | int TGLC_rand_pseudo_bytes (unsigned char *buf, int num); 27 | 28 | #endif 29 | -------------------------------------------------------------------------------- /crypto/rand_altern.c: -------------------------------------------------------------------------------- 1 | /* 2 | This file is part of tgl-library 3 | 4 | This library is free software; you can redistribute it and/or 5 | modify it under the terms of the GNU Lesser General Public 6 | License as published by the Free Software Foundation; either 7 | version 2.1 of the License, or (at your option) any later version. 8 | 9 | This library is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 | Lesser General Public License for more details. 13 | 14 | You should have received a copy of the GNU Lesser General Public 15 | License along with this library; if not, write to the Free Software 16 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 17 | 18 | Copyright Ben Wiederhake 2015 19 | */ 20 | 21 | #include "../config.h" 22 | 23 | #ifdef TGL_AVOID_OPENSSL 24 | 25 | /* Marginally speed up compilation */ 26 | #define GCRYPT_NO_MPI_MACROS 27 | /* Fail-fast when something becomes deprecated. */ 28 | #define GCRYPT_NO_DEPRECATED 29 | 30 | #include 31 | #include 32 | 33 | #include "rand.h" 34 | 35 | void TGLC_rand_add (const void *buf, int num, double entropy) { 36 | (void) entropy; 37 | // TODO: Translate half-broken "entropy" into gcry's "quality". 38 | gcry_random_add_bytes (buf, num, 50); 39 | } 40 | 41 | int TGLC_rand_bytes (unsigned char *buf, int num) { 42 | gcry_randomize (buf, num, GCRY_STRONG_RANDOM); 43 | return 1; // Don't ask why. 44 | } 45 | 46 | int TGLC_rand_pseudo_bytes (unsigned char *buf, int num) { 47 | gcry_create_nonce (buf, num); 48 | return 0; // Don't ask why. 49 | } 50 | 51 | #endif 52 | -------------------------------------------------------------------------------- /crypto/rand_openssl.c: -------------------------------------------------------------------------------- 1 | /* 2 | This file is part of tgl-library 3 | 4 | This library is free software; you can redistribute it and/or 5 | modify it under the terms of the GNU Lesser General Public 6 | License as published by the Free Software Foundation; either 7 | version 2.1 of the License, or (at your option) any later version. 8 | 9 | This library is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 | Lesser General Public License for more details. 13 | 14 | You should have received a copy of the GNU Lesser General Public 15 | License along with this library; if not, write to the Free Software 16 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 17 | 18 | Copyright Ben Wiederhake 2015 19 | */ 20 | 21 | #include "../config.h" 22 | 23 | #ifndef TGL_AVOID_OPENSSL 24 | 25 | #include 26 | 27 | #include "rand.h" 28 | 29 | void TGLC_rand_add (const void *buf, int num, double entropy) { 30 | RAND_add (buf, num, entropy); 31 | } 32 | 33 | int TGLC_rand_bytes (unsigned char *buf, int num) { 34 | return RAND_bytes (buf, num); 35 | } 36 | 37 | int TGLC_rand_pseudo_bytes (unsigned char *buf, int num) { 38 | return RAND_pseudo_bytes (buf, num); 39 | } 40 | 41 | #endif 42 | -------------------------------------------------------------------------------- /crypto/rsa_pem.h: -------------------------------------------------------------------------------- 1 | /* 2 | This file is part of tgl-library 3 | 4 | This library is free software; you can redistribute it and/or 5 | modify it under the terms of the GNU Lesser General Public 6 | License as published by the Free Software Foundation; either 7 | version 2.1 of the License, or (at your option) any later version. 8 | 9 | This library is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 | Lesser General Public License for more details. 13 | 14 | You should have received a copy of the GNU Lesser General Public 15 | License along with this library; if not, write to the Free Software 16 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 17 | 18 | Copyright Ben Wiederhake 2015 19 | */ 20 | 21 | #ifndef __TGL_CRYPTO_RSA_H__ 22 | #define __TGL_CRYPTO_RSA_H__ 23 | 24 | #include /* FILE */ 25 | 26 | #include "bn.h" 27 | 28 | typedef struct TGLC_rsa TGLC_rsa; 29 | 30 | TGLC_rsa *TGLC_rsa_new (unsigned long e, int n_bytes, const unsigned char *n); 31 | 32 | TGLC_bn *TGLC_rsa_n (TGLC_rsa *); 33 | TGLC_bn *TGLC_rsa_e (TGLC_rsa *); 34 | 35 | void TGLC_rsa_free (TGLC_rsa *); 36 | 37 | TGLC_rsa *TGLC_pem_read_RSAPublicKey (FILE *fp); 38 | 39 | #endif 40 | -------------------------------------------------------------------------------- /crypto/rsa_pem_altern.c: -------------------------------------------------------------------------------- 1 | /* 2 | This file is part of tgl-library 3 | 4 | This library is free software; you can redistribute it and/or 5 | modify it under the terms of the GNU Lesser General Public 6 | License as published by the Free Software Foundation; either 7 | version 2.1 of the License, or (at your option) any later version. 8 | 9 | This library is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 | Lesser General Public License for more details. 13 | 14 | You should have received a copy of the GNU Lesser General Public 15 | License along with this library; if not, write to the Free Software 16 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 17 | 18 | Copyright Ben Wiederhake 2015 19 | */ 20 | 21 | #include "../config.h" 22 | 23 | #ifdef TGL_AVOID_OPENSSL 24 | 25 | #include 26 | 27 | #include "meta.h" 28 | #include "rsa_pem.h" 29 | #include "../tools.h" /* talloc */ 30 | 31 | struct TGLC_rsa { 32 | TGLC_bn *n; 33 | TGLC_bn *e; 34 | }; 35 | 36 | TGLC_rsa *TGLC_rsa_new (unsigned long e, int n_bytes, const unsigned char *n) { 37 | assert (n_bytes > 0 && n_bytes < 5000); 38 | TGLC_rsa *ret = talloc (sizeof (TGLC_rsa)); 39 | ret->e = TGLC_bn_new (); 40 | TGLC_bn_set_word (ret->e, e); 41 | ret->n = TGLC_bn_bin2bn (n, n_bytes, NULL); 42 | assert (n_bytes == TGLC_bn_num_bytes (ret->n)); 43 | return ret; 44 | } 45 | 46 | #define RSA_GETTER(M) \ 47 | TGLC_bn *TGLC_rsa_ ## M (TGLC_rsa *key) { \ 48 | return key->M; \ 49 | } \ 50 | 51 | RSA_GETTER(n); 52 | RSA_GETTER(e); 53 | 54 | void TGLC_rsa_free (TGLC_rsa *key) { 55 | if (key->e) { 56 | TGLC_bn_free (key->e); 57 | } 58 | if (key->n) { 59 | TGLC_bn_free (key->n); 60 | } 61 | tfree (key, sizeof (TGLC_rsa)); 62 | } 63 | 64 | TGLC_rsa *TGLC_pem_read_RSAPublicKey (FILE *fp) { 65 | /* 66 | * Reading PEM format involves ASN.1 and is hard. libgcrypt doesn't support it. 67 | * The dependency on oh-so-freaking-much code just to parse static data that 68 | * will never change is not justified. Let the caller figure out how to resolve 69 | * this (telegram-purple does so by using libpurple's built-in functions), and 70 | * ignore any PEM files. 71 | */ 72 | (void) fp; 73 | return NULL; 74 | } 75 | 76 | #endif 77 | -------------------------------------------------------------------------------- /crypto/rsa_pem_openssl.c: -------------------------------------------------------------------------------- 1 | /* 2 | This file is part of tgl-library 3 | 4 | This library is free software; you can redistribute it and/or 5 | modify it under the terms of the GNU Lesser General Public 6 | License as published by the Free Software Foundation; either 7 | version 2.1 of the License, or (at your option) any later version. 8 | 9 | This library is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 | Lesser General Public License for more details. 13 | 14 | You should have received a copy of the GNU Lesser General Public 15 | License along with this library; if not, write to the Free Software 16 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 17 | 18 | Copyright Ben Wiederhake 2015 19 | */ 20 | 21 | #include "../config.h" 22 | 23 | #ifndef TGL_AVOID_OPENSSL 24 | 25 | //#include /* NULL */ 26 | 27 | #include 28 | #include 29 | 30 | #include "bn.h" 31 | #include "meta.h" 32 | #include "rsa_pem.h" 33 | 34 | TGLC_WRAPPER_ASSOC(rsa,RSA) 35 | 36 | // TODO: Refactor crucial struct-identity into its own header. 37 | TGLC_WRAPPER_ASSOC(bn,BIGNUM) 38 | 39 | TGLC_rsa *TGLC_rsa_new (unsigned long e, int n_bytes, const unsigned char *n) { 40 | RSA *ret = RSA_new (); 41 | ret->e = unwrap_bn (TGLC_bn_new ()); 42 | TGLC_bn_set_word (wrap_bn (ret->e), e); 43 | ret->n = unwrap_bn (TGLC_bn_bin2bn (n, n_bytes, NULL)); 44 | return wrap_rsa (ret); 45 | } 46 | 47 | #define RSA_GETTER(M) \ 48 | TGLC_bn *TGLC_rsa_ ## M (TGLC_rsa *key) { \ 49 | return wrap_bn (unwrap_rsa (key)->M); \ 50 | } \ 51 | 52 | RSA_GETTER(n); 53 | RSA_GETTER(e); 54 | 55 | void TGLC_rsa_free (TGLC_rsa *p) { 56 | RSA_free (unwrap_rsa (p)); 57 | } 58 | 59 | TGLC_rsa *TGLC_pem_read_RSAPublicKey (FILE *fp) { 60 | return wrap_rsa (PEM_read_RSAPublicKey (fp, NULL, NULL, NULL)); 61 | } 62 | 63 | #endif 64 | -------------------------------------------------------------------------------- /crypto/sha.h: -------------------------------------------------------------------------------- 1 | /* 2 | This file is part of tgl-library 3 | 4 | This library is free software; you can redistribute it and/or 5 | modify it under the terms of the GNU Lesser General Public 6 | License as published by the Free Software Foundation; either 7 | version 2.1 of the License, or (at your option) any later version. 8 | 9 | This library is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 | Lesser General Public License for more details. 13 | 14 | You should have received a copy of the GNU Lesser General Public 15 | License along with this library; if not, write to the Free Software 16 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 17 | 18 | Copyright Ben Wiederhake 2015 19 | */ 20 | 21 | #ifndef __TGL_CRYPTO_SHA_H__ 22 | #define __TGL_CRYPTO_SHA_H__ 23 | 24 | #include /* size_t */ 25 | 26 | void TGLC_sha1 (const unsigned char *d, size_t n, unsigned char *md); 27 | void TGLC_sha256 (const unsigned char *d, size_t n, unsigned char *md); 28 | 29 | #endif 30 | -------------------------------------------------------------------------------- /crypto/sha_altern.c: -------------------------------------------------------------------------------- 1 | /* 2 | This file is part of tgl-library 3 | 4 | This library is free software; you can redistribute it and/or 5 | modify it under the terms of the GNU Lesser General Public 6 | License as published by the Free Software Foundation; either 7 | version 2.1 of the License, or (at your option) any later version. 8 | 9 | This library is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 | Lesser General Public License for more details. 13 | 14 | You should have received a copy of the GNU Lesser General Public 15 | License along with this library; if not, write to the Free Software 16 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 17 | 18 | Copyright Ben Wiederhake 2015 19 | */ 20 | 21 | #include "../config.h" 22 | 23 | #ifdef TGL_AVOID_OPENSSL 24 | 25 | /* Marginally speed up compilation */ 26 | #define GCRYPT_NO_MPI_MACROS 27 | /* Fail-fast when something becomes deprecated. */ 28 | #define GCRYPT_NO_DEPRECATED 29 | 30 | #include 31 | 32 | #include "sha.h" 33 | 34 | void TGLC_sha1 (const unsigned char *d, size_t n, unsigned char *md) { 35 | gcry_md_hash_buffer (GCRY_MD_SHA1, md, d, n); 36 | } 37 | void TGLC_sha256 (const unsigned char *d, size_t n, unsigned char *md) { 38 | gcry_md_hash_buffer (GCRY_MD_SHA256, md, d, n); 39 | } 40 | 41 | #endif 42 | -------------------------------------------------------------------------------- /crypto/sha_openssl.c: -------------------------------------------------------------------------------- 1 | /* 2 | This file is part of tgl-library 3 | 4 | This library is free software; you can redistribute it and/or 5 | modify it under the terms of the GNU Lesser General Public 6 | License as published by the Free Software Foundation; either 7 | version 2.1 of the License, or (at your option) any later version. 8 | 9 | This library is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 | Lesser General Public License for more details. 13 | 14 | You should have received a copy of the GNU Lesser General Public 15 | License along with this library; if not, write to the Free Software 16 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 17 | 18 | Copyright Ben Wiederhake 2015 19 | */ 20 | 21 | #include "../config.h" 22 | 23 | #ifndef TGL_AVOID_OPENSSL 24 | 25 | #include 26 | 27 | #include "sha.h" 28 | 29 | void TGLC_sha1 (const unsigned char *d, size_t n, unsigned char *md) { 30 | SHA1 (d, n, md); 31 | } 32 | void TGLC_sha256 (const unsigned char *d, size_t n, unsigned char *md) { 33 | SHA256 (d, n, md); 34 | } 35 | 36 | #endif 37 | -------------------------------------------------------------------------------- /encrypted_scheme.tl: -------------------------------------------------------------------------------- 1 | ---types--- 2 | decryptedMessageMediaEmpty#89f5c4a = DecryptedMessageMedia; 3 | decryptedMessageMediaPhoto#32798a8c str_thumb:bytes thumb_w:int thumb_h:int w:int h:int size:int key:bytes iv:bytes = DecryptedMessageMedia; 4 | decryptedMessageMediaGeoPoint#35480a59 latitude:double longitude:double = DecryptedMessageMedia; 5 | decryptedMessageMediaContact#588a0a97 phone_number:string first_name:string last_name:string user_id:int = DecryptedMessageMedia; 6 | decryptedMessageActionSetMessageTTL#a1733aec ttl_seconds:int = DecryptedMessageAction; 7 | decryptedMessageMediaDocument#b095434b str_thumb:bytes thumb_w:int thumb_h:int file_name:string mime_type:string size:int key:bytes iv:bytes = DecryptedMessageMedia; 8 | decryptedMessageActionReadMessages#c4f40be random_ids:Vector = DecryptedMessageAction; 9 | decryptedMessageActionDeleteMessages#65614304 random_ids:Vector = DecryptedMessageAction; 10 | decryptedMessageActionScreenshotMessages#8ac1f475 random_ids:Vector = DecryptedMessageAction; 11 | decryptedMessageActionFlushHistory#6719e45c = DecryptedMessageAction; 12 | 13 | decryptedMessage#204d3878 random_id:long ttl:int message:string media:DecryptedMessageMedia = DecryptedMessage; 14 | decryptedMessageService#73164160 random_id:long action:DecryptedMessageAction = DecryptedMessage; 15 | decryptedMessageMediaVideo#524a415d str_thumb:bytes thumb_w:int thumb_h:int duration:int mime_type:string w:int h:int size:int key:bytes iv:bytes = DecryptedMessageMedia; 16 | decryptedMessageMediaAudio#57e0a9cb duration:int mime_type:string size:int key:bytes iv:bytes = DecryptedMessageMedia; 17 | decryptedMessageLayer#1be31789 random_bytes:bytes layer:int in_seq_no:int out_seq_no:int message:DecryptedMessage = DecryptedMessageLayer; 18 | decryptedMessageActionResend#511110b0 start_seq_no:int end_seq_no:int = DecryptedMessageAction; 19 | decryptedMessageActionNotifyLayer#f3048883 layer:int = DecryptedMessageAction; 20 | decryptedMessageActionTyping#ccb27641 action:SendMessageAction = DecryptedMessageAction; 21 | 22 | decryptedMessageActionRequestKey#f3c9611b exchange_id:long g_a:bytes = DecryptedMessageAction; 23 | decryptedMessageActionAcceptKey#6fe1735b exchange_id:long g_b:bytes key_fingerprint:long = DecryptedMessageAction; 24 | decryptedMessageActionAbortKey#dd05ec6b exchange_id:long = DecryptedMessageAction; 25 | decryptedMessageActionCommitKey#ec2e0b9b exchange_id:long key_fingerprint:long = DecryptedMessageAction; 26 | decryptedMessageActionNoop#a82fdd63 = DecryptedMessageAction; 27 | 28 | decryptedMessageMediaExternalDocument#fa95b0dd id:long access_hash:long date:int mime_type:string size:int thumb:PhotoSize dc_id:int attributes:Vector = DecryptedMessageMedia; 29 | ---functions--- 30 | -------------------------------------------------------------------------------- /errors: -------------------------------------------------------------------------------- 1 | type of errors that tgl can set: 2 | 3 | EPROTO: server returned error for query. Some kinds of error (such as FLOOD_WAIT) tgl can handle by itself, but others it can not. In most cases it means bug in tgl or invalid parameter supplied to method (such as message id). On BSD, EPROTO is not defined. Whenever EPROTO is not #define'd, tgl uses EIO instead. 4 | 5 | EINVAL: tgl detected invalid argument supplied before sending query to server. For example user instead of chat or bad msg id. 6 | 7 | ENOENT: tgl received empty response from server. For example when user tried to get message by id 8 | 9 | EBADF: tgl can not open file on disk or file is empty 10 | 11 | E2BIG: supplied file is too big 12 | 13 | ENOTCONN: no public keys available 14 | -------------------------------------------------------------------------------- /event-old.h: -------------------------------------------------------------------------------- 1 | #ifndef __EVENT_OLD_H__ 2 | #define __EVENT_OLD_H__ 3 | 4 | #include 5 | #include 6 | 7 | #define BEV_EVENT_READ EVBUFFER_READ 8 | #define BEV_EVENT_WRITE EVBUFFER_WRITE 9 | #define BEV_EVENT_EOF EVBUFFER_EOF 10 | #define BEV_EVENT_ERROR EVBUFFER_ERROR 11 | #define BEV_EVENT_TIMEOUT EVBUFFER_TIMEOUT 12 | 13 | typedef int evutil_socket_t; 14 | 15 | static inline struct event *event_new (struct event_base *base, int fd, int what, void(*callback)(int, short, void *), void *arg) __attribute__ ((unused)); 16 | static inline struct event *event_new (struct event_base *base, int fd, int what, void(*callback)(int, short, void *), void *arg) { 17 | struct event *ev = malloc (sizeof (*ev)); 18 | event_set (ev, fd, what, callback, arg); 19 | event_base_set (base, ev); 20 | return ev; 21 | } 22 | 23 | static inline struct event *evtimer_new (struct event_base *base, void(*callback)(int, short, void *), void *arg) __attribute__ ((unused)); 24 | static inline struct event *evtimer_new (struct event_base *base, void(*callback)(int, short, void *), void *arg) { 25 | struct event *ev = malloc (sizeof (*ev)); 26 | event_set (ev, -1, 0, callback, arg); 27 | event_base_set (base, ev); 28 | return ev; 29 | } 30 | 31 | static void event_free (struct event *ev) __attribute__ ((unused)); 32 | static void event_free (struct event *ev) { 33 | event_del (ev); 34 | free (ev); 35 | } 36 | 37 | static struct bufferevent *bufferevent_socket_new (struct event_base *base, int fd, int flags) __attribute__ ((unused)); 38 | static struct bufferevent *bufferevent_socket_new (struct event_base *base, int fd, int flags) { 39 | assert (!flags); 40 | struct bufferevent *bev = bufferevent_new(fd, 0, 0, 0, 0); 41 | bufferevent_base_set (base, bev); 42 | return bev; 43 | } 44 | 45 | static inline void *event_get_callback_arg(const struct event *ev) { 46 | return ev->ev_arg; 47 | } 48 | #endif 49 | -------------------------------------------------------------------------------- /gen_constants_h.awk: -------------------------------------------------------------------------------- 1 | BEGIN { 2 | print "/*"; 3 | print " This file is part of telegram-client."; 4 | print ""; 5 | print " Telegram-client is free software: you can redistribute it and/or modify"; 6 | print " it under the terms of the GNU General Public License as published by"; 7 | print " the Free Software Foundation, either version 2 of the License, or"; 8 | print " (at your option) any later version."; 9 | print ""; 10 | print " Telegram-client is distributed in the hope that it will be useful,"; 11 | print " but WITHOUT ANY WARRANTY; without even the implied warranty of"; 12 | print " MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the"; 13 | print " GNU General Public License for more details."; 14 | print ""; 15 | print " You should have received a copy of the GNU General Public License"; 16 | print " along with this telegram-client. If not, see ."; 17 | print ""; 18 | print " Copyright Vitaly Valtman 2013"; 19 | print "*/"; 20 | print "#ifndef CONSTANTS_H"; 21 | print "#define CONSTANTS_H"; 22 | } 23 | // { 24 | if (split ($1, a, "#") == 2) { 25 | gsub (/[ABCDEFGHIJKLMNOPQRSTUVWXYZ]/, "_&", a[1]); 26 | gsub (/[.]/, "_", a[1]); 27 | if (a[2] in h) { 28 | print "ERROR: Duplicate magic " a[2] " for define " a[1] " and " h[a[2]] > "/dev/stderr" 29 | exit 1; 30 | } 31 | h[a[2]] = a[1]; 32 | print "#define", "CODE_" tolower(a[1]), "0x" a[2]; 33 | } 34 | } 35 | END { 36 | print "#endif"; 37 | } 38 | -------------------------------------------------------------------------------- /generate.h: -------------------------------------------------------------------------------- 1 | /* 2 | This file is part of tgl-libary/generate 3 | 4 | Tgl-library/generate is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 2 of the License, or 7 | (at your option) any later version. 8 | 9 | Tgl-library/generate is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | along with this tgl-library/generate. If not, see . 16 | 17 | Copyright Vitaly Valtman 2014-2015 18 | 19 | It is derivative work of VK/KittenPHP-DB-Engine (https://github.com/vk-com/kphp-kdb/) 20 | Copyright 2012-2013 Vkontakte Ltd 21 | 2012-2013 Vitaliy Valtman 22 | */ 23 | 24 | #ifndef __GENERATE_H__ 25 | #define __GENERATE_H__ 26 | 27 | struct tl_combinator; 28 | 29 | struct tl_type { 30 | // struct tl_type_methods *methods; 31 | char *id; 32 | char *print_id; 33 | unsigned name; 34 | int arity; 35 | int flags; 36 | int constructors_num; 37 | struct tl_combinator **constructors; 38 | long long params_types; 39 | int extra; 40 | }; 41 | 42 | #define NODE_TYPE_TYPE 1 43 | #define NODE_TYPE_NAT_CONST 2 44 | #define NODE_TYPE_VAR_TYPE 3 45 | #define NODE_TYPE_VAR_NUM 4 46 | #define NODE_TYPE_ARRAY 5 47 | 48 | #define MAX_COMBINATOR_VARS 64 49 | 50 | #define NAME_VAR_NUM 0x70659eff 51 | #define NAME_VAR_TYPE 0x2cecf817 52 | #define NAME_INT 0xa8509bda 53 | #define NAME_LONG 0x22076cba 54 | #define NAME_DOUBLE 0x2210c154 55 | #define NAME_STRING 0xb5286e24 56 | #define NAME_VECTOR 0x1cb5c415 57 | #define NAME_MAYBE_TRUE 0x3f9c8ef8 58 | #define NAME_MAYBE_FALSE 0x27930a7b 59 | #define NAME_BOOL_FALSE 0xbc799737 60 | #define NAME_BOOL_TRUE 0x997275b5 61 | #define NAME_BYTES 0x0ee1379f 62 | 63 | 64 | #define FLAG_OPT_VAR (1 << 17) 65 | #define FLAG_EXCL (1 << 18) 66 | #define FLAG_OPT_FIELD (1 << 20) 67 | #define FLAG_NOVAR (1 << 21) 68 | #define FLAG_BARE 1 69 | #define FLAGS_MASK ((1 << 16) - 1) 70 | #define FLAG_DEFAULT_CONSTRUCTOR (1 << 25) 71 | #define FLAG_NOCONS (1 << 1) 72 | 73 | extern struct tl_tree_methods tl_nat_const_methods; 74 | extern struct tl_tree_methods tl_nat_const_full_methods; 75 | extern struct tl_tree_methods tl_pnat_const_full_methods; 76 | extern struct tl_tree_methods tl_array_methods; 77 | extern struct tl_tree_methods tl_type_methods; 78 | extern struct tl_tree_methods tl_parray_methods; 79 | extern struct tl_tree_methods tl_ptype_methods; 80 | extern struct tl_tree_methods tl_var_num_methods; 81 | extern struct tl_tree_methods tl_var_type_methods; 82 | extern struct tl_tree_methods tl_pvar_num_methods; 83 | extern struct tl_tree_methods tl_pvar_type_methods; 84 | #define TL_IS_NAT_VAR(x) (((long)x) & 1) 85 | #define TL_TREE_METHODS(x) (TL_IS_NAT_VAR (x) ? &tl_nat_const_methods : ((struct tl_tree *)(x))->methods) 86 | 87 | #define DEC_REF(x) (TL_TREE_METHODS(x)->dec_ref ((void *)x)) 88 | #define INC_REF(x) (TL_TREE_METHODS(x)->inc_ref ((void *)x)) 89 | #define TYPE(x) (TL_TREE_METHODS(x)->type ((void *)x)) 90 | 91 | typedef unsigned long long tl_tree_hash_t; 92 | struct tl_tree; 93 | 94 | struct tl_tree_methods { 95 | int (*type)(struct tl_tree *T); 96 | int (*eq)(struct tl_tree *T, struct tl_tree *U); 97 | void (*inc_ref)(struct tl_tree *T); 98 | void (*dec_ref)(struct tl_tree *T); 99 | }; 100 | 101 | struct tl_tree { 102 | int ref_cnt; 103 | int flags; 104 | //tl_tree_hash_t hash; 105 | struct tl_tree_methods *methods; 106 | }; 107 | /* 108 | struct tl_tree_nat_const { 109 | struct tl_tree self; 110 | int value; 111 | };*/ 112 | 113 | struct tl_tree_type { 114 | struct tl_tree self; 115 | 116 | struct tl_type *type; 117 | int children_num; 118 | struct tl_tree **children; 119 | }; 120 | 121 | struct tl_tree_array { 122 | struct tl_tree self; 123 | 124 | struct tl_tree *multiplicity; 125 | int args_num; 126 | struct arg **args; 127 | }; 128 | 129 | struct tl_tree_var_type { 130 | struct tl_tree self; 131 | 132 | int var_num; 133 | }; 134 | 135 | struct tl_tree_var_num { 136 | struct tl_tree self; 137 | 138 | int var_num; 139 | int dif; 140 | }; 141 | 142 | struct tl_tree_nat_const { 143 | struct tl_tree self; 144 | 145 | long long value; 146 | }; 147 | 148 | struct arg { 149 | char *id; 150 | int var_num; 151 | int flags; 152 | int exist_var_num; 153 | int exist_var_bit; 154 | struct tl_tree *type; 155 | }; 156 | 157 | struct tl_combinator { 158 | //struct tl_combinator_methods *methods; 159 | char *id; 160 | char *print_id; 161 | unsigned name; 162 | int is_fun; 163 | int var_num; 164 | int args_num; 165 | struct arg **args; 166 | struct tl_tree *result; 167 | void **IP; 168 | void **fIP; 169 | int IP_len; 170 | int fIP_len; 171 | }; 172 | 173 | #endif 174 | -------------------------------------------------------------------------------- /m4_ax_check_openssl.m4: -------------------------------------------------------------------------------- 1 | # =========================================================================== 2 | # http://www.gnu.org/software/autoconf-archive/ax_check_openssl.html 3 | # =========================================================================== 4 | # 5 | # SYNOPSIS 6 | # 7 | # AX_CHECK_OPENSSL([action-if-found[, action-if-not-found]]) 8 | # 9 | # DESCRIPTION 10 | # 11 | # Look for OpenSSL in a number of default spots, or in a user-selected 12 | # spot (via --with-openssl). Sets 13 | # 14 | # OPENSSL_INCLUDES to the include directives required 15 | # OPENSSL_LIBS to the -l directives required 16 | # OPENSSL_LDFLAGS to the -L or -R flags required 17 | # 18 | # and calls ACTION-IF-FOUND or ACTION-IF-NOT-FOUND appropriately 19 | # 20 | # This macro sets OPENSSL_INCLUDES such that source files should use the 21 | # openssl/ directory in include directives: 22 | # 23 | # #include 24 | # 25 | # LICENSE 26 | # 27 | # Copyright (c) 2009,2010 Zmanda Inc. 28 | # Copyright (c) 2009,2010 Dustin J. Mitchell 29 | # 30 | # Copying and distribution of this file, with or without modification, are 31 | # permitted in any medium without royalty provided the copyright notice 32 | # and this notice are preserved. This file is offered as-is, without any 33 | # warranty. 34 | 35 | #serial 8 36 | 37 | AU_ALIAS([CHECK_SSL], [AX_CHECK_OPENSSL]) 38 | AC_DEFUN([AX_CHECK_OPENSSL], [ 39 | found=false 40 | AC_ARG_WITH([openssl], 41 | [AS_HELP_STRING([--with-openssl=DIR], 42 | [root of the OpenSSL directory])], 43 | [ 44 | case "$withval" in 45 | "" | y | ye | yes | n | no) 46 | AC_MSG_ERROR([Invalid --with-openssl value]) 47 | ;; 48 | *) ssldirs="$withval" 49 | ;; 50 | esac 51 | ], [ 52 | # if pkg-config is installed and openssl has installed a .pc file, 53 | # then use that information and don't search ssldirs 54 | AC_PATH_PROG([PKG_CONFIG], [pkg-config]) 55 | if test x"$PKG_CONFIG" != x""; then 56 | OPENSSL_LDFLAGS=`$PKG_CONFIG openssl --libs-only-L 2>/dev/null` 57 | if test $? = 0; then 58 | OPENSSL_LIBS=`$PKG_CONFIG openssl --libs-only-l 2>/dev/null` 59 | OPENSSL_INCLUDES=`$PKG_CONFIG openssl --cflags-only-I 2>/dev/null` 60 | found=true 61 | fi 62 | fi 63 | 64 | # no such luck; use some default ssldirs 65 | if ! $found; then 66 | ssldirs="/usr/local/ssl /usr/lib/ssl /usr/ssl /usr/pkg /usr/local /usr" 67 | fi 68 | ] 69 | ) 70 | 71 | 72 | # note that we #include , so the OpenSSL headers have to be in 73 | # an 'openssl' subdirectory 74 | 75 | if ! $found; then 76 | OPENSSL_INCLUDES= 77 | for ssldir in $ssldirs; do 78 | AC_MSG_CHECKING([for openssl/ssl.h in $ssldir]) 79 | if test -f "$ssldir/include/openssl/ssl.h"; then 80 | OPENSSL_INCLUDES="-I$ssldir/include" 81 | OPENSSL_LDFLAGS="-L$ssldir/lib" 82 | OPENSSL_LIBS="-lssl -lcrypto" 83 | found=true 84 | AC_MSG_RESULT([yes]) 85 | break 86 | else 87 | AC_MSG_RESULT([no]) 88 | fi 89 | done 90 | 91 | # if the file wasn't found, well, go ahead and try the link anyway -- maybe 92 | # it will just work! 93 | fi 94 | 95 | # try the preprocessor and linker with our new flags, 96 | # being careful not to pollute the global LIBS, LDFLAGS, and CPPFLAGS 97 | 98 | AC_MSG_CHECKING([whether compiling and linking against OpenSSL works]) 99 | echo "Trying link with OPENSSL_LDFLAGS=$OPENSSL_LDFLAGS;" \ 100 | "OPENSSL_LIBS=$OPENSSL_LIBS; OPENSSL_INCLUDES=$OPENSSL_INCLUDES" >&AS_MESSAGE_LOG_FD 101 | 102 | save_LIBS="$LIBS" 103 | save_LDFLAGS="$LDFLAGS" 104 | save_CPPFLAGS="$CPPFLAGS" 105 | LDFLAGS="$LDFLAGS $OPENSSL_LDFLAGS" 106 | LIBS="$OPENSSL_LIBS $LIBS" 107 | CPPFLAGS="$OPENSSL_INCLUDES $CPPFLAGS" 108 | AC_LINK_IFELSE( 109 | [AC_LANG_PROGRAM([#include ], [SSL_new(NULL)])], 110 | [ 111 | AC_MSG_RESULT([yes]) 112 | $1 113 | ], [ 114 | AC_MSG_RESULT([no]) 115 | $2 116 | ]) 117 | CPPFLAGS="$save_CPPFLAGS" 118 | LDFLAGS="$save_LDFLAGS" 119 | LIBS="$save_LIBS" 120 | 121 | AC_SUBST([OPENSSL_INCLUDES]) 122 | AC_SUBST([OPENSSL_LIBS]) 123 | AC_SUBST([OPENSSL_LDFLAGS]) 124 | ]) 125 | -------------------------------------------------------------------------------- /m4_ax_check_zlib.m4: -------------------------------------------------------------------------------- 1 | # =========================================================================== 2 | # http://www.gnu.org/software/autoconf-archive/ax_check_zlib.html 3 | # =========================================================================== 4 | # 5 | # SYNOPSIS 6 | # 7 | # AX_CHECK_ZLIB([action-if-found], [action-if-not-found]) 8 | # 9 | # DESCRIPTION 10 | # 11 | # This macro searches for an installed zlib library. If nothing was 12 | # specified when calling configure, it searches first in /usr/local and 13 | # then in /usr, /opt/local and /sw. If the --with-zlib=DIR is specified, 14 | # it will try to find it in DIR/include/zlib.h and DIR/lib/libz.a. If 15 | # --without-zlib is specified, the library is not searched at all. 16 | # 17 | # If either the header file (zlib.h) or the library (libz) is not found, 18 | # shell commands 'action-if-not-found' is run. If 'action-if-not-found' is 19 | # not specified, the configuration exits on error, asking for a valid zlib 20 | # installation directory or --without-zlib. 21 | # 22 | # If both header file and library are found, shell commands 23 | # 'action-if-found' is run. If 'action-if-found' is not specified, the 24 | # default action appends '-I${ZLIB_HOME}/include' to CPFLAGS, appends 25 | # '-L$ZLIB_HOME}/lib' to LDFLAGS, prepends '-lz' to LIBS, and calls 26 | # AC_DEFINE(HAVE_LIBZ). You should use autoheader to include a definition 27 | # for this symbol in a config.h file. Sample usage in a C/C++ source is as 28 | # follows: 29 | # 30 | # #ifdef HAVE_LIBZ 31 | # #include 32 | # #endif /* HAVE_LIBZ */ 33 | # 34 | # LICENSE 35 | # 36 | # Copyright (c) 2008 Loic Dachary 37 | # Copyright (c) 2010 Bastien Chevreux 38 | # 39 | # This program is free software; you can redistribute it and/or modify it 40 | # under the terms of the GNU General Public License as published by the 41 | # Free Software Foundation; either version 2 of the License, or (at your 42 | # option) any later version. 43 | # 44 | # This program is distributed in the hope that it will be useful, but 45 | # WITHOUT ANY WARRANTY; without even the implied warranty of 46 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General 47 | # Public License for more details. 48 | # 49 | # You should have received a copy of the GNU General Public License along 50 | # with this program. If not, see . 51 | # 52 | # As a special exception, the respective Autoconf Macro's copyright owner 53 | # gives unlimited permission to copy, distribute and modify the configure 54 | # scripts that are the output of Autoconf when processing the Macro. You 55 | # need not follow the terms of the GNU General Public License when using 56 | # or distributing such scripts, even though portions of the text of the 57 | # Macro appear in them. The GNU General Public License (GPL) does govern 58 | # all other use of the material that constitutes the Autoconf Macro. 59 | # 60 | # This special exception to the GPL applies to versions of the Autoconf 61 | # Macro released by the Autoconf Archive. When you make and distribute a 62 | # modified version of the Autoconf Macro, you may extend this special 63 | # exception to the GPL to apply to your modified version as well. 64 | 65 | #serial 14 66 | 67 | AU_ALIAS([CHECK_ZLIB], [AX_CHECK_ZLIB]) 68 | AC_DEFUN([AX_CHECK_ZLIB], 69 | # 70 | # Handle user hints 71 | # 72 | [AC_MSG_CHECKING(if zlib is wanted) 73 | zlib_places="/usr/local /usr /opt/local /sw" 74 | AC_ARG_WITH([zlib], 75 | [ --with-zlib=DIR root directory path of zlib installation @<:@defaults to 76 | /usr/local or /usr if not found in /usr/local@:>@ 77 | --without-zlib to disable zlib usage completely], 78 | [if test "$withval" != no ; then 79 | AC_MSG_RESULT(yes) 80 | if test -d "$withval" 81 | then 82 | zlib_places="$withval $zlib_places" 83 | else 84 | AC_MSG_WARN([Sorry, $withval does not exist, checking usual places]) 85 | fi 86 | else 87 | zlib_places= 88 | AC_MSG_RESULT(no) 89 | fi], 90 | [AC_MSG_RESULT(yes)]) 91 | 92 | # 93 | # Locate zlib, if wanted 94 | # 95 | if test -n "${zlib_places}" 96 | then 97 | # check the user supplied or any other more or less 'standard' place: 98 | # Most UNIX systems : /usr/local and /usr 99 | # MacPorts / Fink on OSX : /opt/local respectively /sw 100 | for ZLIB_HOME in ${zlib_places} ; do 101 | if test -f "${ZLIB_HOME}/include/zlib.h"; then break; fi 102 | ZLIB_HOME="" 103 | done 104 | 105 | ZLIB_OLD_LDFLAGS=$LDFLAGS 106 | ZLIB_OLD_CPPFLAGS=$CPPFLAGS 107 | if test -n "${ZLIB_HOME}"; then 108 | LDFLAGS="$LDFLAGS -L${ZLIB_HOME}/lib" 109 | CPPFLAGS="$CPPFLAGS -I${ZLIB_HOME}/include" 110 | fi 111 | AC_LANG_SAVE 112 | AC_LANG_C 113 | AC_CHECK_LIB([z], [inflateEnd], [zlib_cv_libz=yes], [zlib_cv_libz=no]) 114 | AC_CHECK_HEADER([zlib.h], [zlib_cv_zlib_h=yes], [zlib_cv_zlib_h=no]) 115 | AC_LANG_RESTORE 116 | if test "$zlib_cv_libz" = "yes" && test "$zlib_cv_zlib_h" = "yes" 117 | then 118 | # 119 | # If both library and header were found, action-if-found 120 | # 121 | m4_ifblank([$1],[ 122 | CPPFLAGS="$CPPFLAGS -I${ZLIB_HOME}/include" 123 | LDFLAGS="$LDFLAGS -L${ZLIB_HOME}/lib" 124 | LIBS="-lz $LIBS" 125 | AC_DEFINE([HAVE_LIBZ], [1], 126 | [Define to 1 if you have `z' library (-lz)]) 127 | ],[ 128 | # Restore variables 129 | LDFLAGS="$ZLIB_OLD_LDFLAGS" 130 | CPPFLAGS="$ZLIB_OLD_CPPFLAGS" 131 | $1 132 | ]) 133 | else 134 | # 135 | # If either header or library was not found, action-if-not-found 136 | # 137 | m4_default([$2],[ 138 | AC_MSG_ERROR([either specify a valid zlib installation with --with-zlib=DIR or disable zlib usage with --without-zlib]) 139 | ]) 140 | fi 141 | fi 142 | ]) 143 | -------------------------------------------------------------------------------- /mtproto-client.h: -------------------------------------------------------------------------------- 1 | /* 2 | This file is part of tgl-library 3 | 4 | This library is free software; you can redistribute it and/or 5 | modify it under the terms of the GNU Lesser General Public 6 | License as published by the Free Software Foundation; either 7 | version 2.1 of the License, or (at your option) any later version. 8 | 9 | This library is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 | Lesser General Public License for more details. 13 | 14 | You should have received a copy of the GNU Lesser General Public 15 | License along with this library; if not, write to the Free Software 16 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 17 | 18 | Copyright Nikolay Durov, Andrey Lopatin 2012-2013 19 | Vitaly Valtman 2013-2015 20 | */ 21 | #ifndef __MTPROTO_CLIENT_H__ 22 | #define __MTPROTO_CLIENT_H__ 23 | //#include "net.h" 24 | #include "crypto/bn.h" 25 | //void on_start (void); 26 | //..long long encrypt_send_message (struct connection *c, int *msg, int msg_ints, int useful); 27 | //void dc_authorize (struct tgl_dc *DC); 28 | //void work_update (struct connection *c, long long msg_id); 29 | //void work_update_binlog (void); 30 | //int check_g (unsigned char p[256], BIGNUM *g); 31 | //int check_g_bn (BIGNUM *p, BIGNUM *g); 32 | //int check_DH_params (BIGNUM *p, int g); 33 | //void secure_random (void *s, int l); 34 | 35 | #include "tgl.h" 36 | 37 | struct connection; 38 | struct tgl_dc; 39 | //#include "queries.h" 40 | #define TG_APP_HASH "844584f2b1fd2daecee726166dcc1ef8" 41 | #define TG_APP_ID 10534 42 | 43 | #define ACK_TIMEOUT 1 44 | #define MAX_DC_ID 10 45 | 46 | struct connection; 47 | 48 | long long tglmp_encrypt_send_message (struct tgl_state *TLS, struct connection *c, int *msg, int msg_ints, int flags); 49 | void tglmp_dc_create_session (struct tgl_state *TLS, struct tgl_dc *DC); 50 | //int tglmp_check_g (struct tgl_state *TLS, unsigned char p[256], BIGNUM *g); 51 | //int tglmp_check_DH_params (struct tgl_state *TLS, BIGNUM *p, int g); 52 | struct tgl_dc *tglmp_alloc_dc (struct tgl_state *TLS, int flags, int id, char *ip, int port); 53 | void tglmp_regenerate_temp_auth_key (struct tgl_state *TLS, struct tgl_dc *D); 54 | 55 | void tgln_insert_msg_id (struct tgl_state *TLS, struct tgl_session *S, long long id); 56 | int tglmp_on_start (struct tgl_state *TLS); 57 | void tgl_dc_authorize (struct tgl_state *TLS, struct tgl_dc *DC); 58 | void tgls_free_dc (struct tgl_state *TLS, struct tgl_dc *DC); 59 | void tgls_free_pubkey (struct tgl_state *TLS); 60 | void tgl_do_send_ping (struct tgl_state *TLS, struct connection *c); 61 | #endif 62 | -------------------------------------------------------------------------------- /mtproto-common.c: -------------------------------------------------------------------------------- 1 | /* 2 | This file is part of tgl-library 3 | 4 | This library is free software; you can redistribute it and/or 5 | modify it under the terms of the GNU Lesser General Public 6 | License as published by the Free Software Foundation; either 7 | version 2.1 of the License, or (at your option) any later version. 8 | 9 | This library is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 | Lesser General Public License for more details. 13 | 14 | You should have received a copy of the GNU Lesser General Public 15 | License along with this library; if not, write to the Free Software 16 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 17 | 18 | Copyright Nikolay Durov, Andrey Lopatin 2012-2013 19 | Vitaly Valtman 2013-2015 20 | */ 21 | 22 | #ifdef HAVE_CONFIG_H 23 | #include "config.h" 24 | #endif 25 | 26 | #define _FILE_OFFSET_BITS 64 27 | 28 | #include 29 | #include 30 | #include 31 | #include 32 | #include 33 | #include 34 | #include 35 | #ifdef WIN32 36 | #include 37 | #else 38 | #include 39 | #endif 40 | 41 | #include "crypto/aes.h" 42 | #include "crypto/rand.h" 43 | #include "crypto/sha.h" 44 | 45 | #include "mtproto-common.h" 46 | #include "tools.h" 47 | 48 | #ifdef __MACH__ 49 | #include 50 | #include 51 | #endif 52 | 53 | #include 54 | 55 | #ifndef O_BINARY 56 | #define O_BINARY 0 57 | #endif 58 | 59 | static int __packet_buffer[PACKET_BUFFER_SIZE + 16]; 60 | int *tgl_packet_ptr; 61 | int *tgl_packet_buffer = __packet_buffer + 16; 62 | 63 | static long long rsa_encrypted_chunks, rsa_decrypted_chunks; 64 | 65 | //int verbosity; 66 | 67 | #ifndef WIN32 68 | static int get_random_bytes (struct tgl_state *TLS, unsigned char *buf, int n) { 69 | int r = 0, h = open ("/dev/random", O_RDONLY | O_NONBLOCK); 70 | if (h >= 0) { 71 | r = read (h, buf, n); 72 | if (r > 0) { 73 | vlogprintf (E_DEBUG, "added %d bytes of real entropy to secure random numbers seed\n", r); 74 | } else { 75 | r = 0; 76 | } 77 | close (h); 78 | } 79 | 80 | if (r < n) { 81 | h = open ("/dev/urandom", O_RDONLY); 82 | if (h < 0) { 83 | return r; 84 | } 85 | int s = read (h, buf + r, n - r); 86 | close (h); 87 | if (s > 0) { 88 | r += s; 89 | } 90 | } 91 | 92 | if (r >= (int) sizeof (long)) { 93 | *(long *)buf ^= lrand48 (); 94 | srand48 (*(long *)buf); 95 | } 96 | 97 | return r; 98 | } 99 | #else 100 | static HCRYPTPROV hCryptoServiceProvider = 0; 101 | static int get_random_bytes (struct tgl_state *TLS, unsigned char *buf, int n) { 102 | if (hCryptoServiceProvider == 0) { 103 | /* Crypto init */ 104 | CryptAcquireContextA(&hCryptoServiceProvider, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT); 105 | } 106 | 107 | if (!CryptGenRandom(hCryptoServiceProvider, n, buf)) { 108 | return -1; 109 | } 110 | 111 | 112 | return n; 113 | } 114 | #endif 115 | 116 | 117 | /* RDTSC */ 118 | #if defined(__i386__) 119 | #define HAVE_RDTSC 120 | static __inline__ unsigned long long rdtsc (void) { 121 | unsigned long long int x; 122 | __asm__ volatile ("rdtsc" : "=A" (x)); 123 | return x; 124 | } 125 | #elif defined(__x86_64__) 126 | #define HAVE_RDTSC 127 | static __inline__ unsigned long long rdtsc (void) { 128 | unsigned hi, lo; 129 | __asm__ __volatile__ ("rdtsc" : "=a"(lo), "=d"(hi)); 130 | return ((unsigned long long) lo) | (((unsigned long long) hi) << 32); 131 | } 132 | #endif 133 | 134 | void tgl_prng_seed (struct tgl_state *TLS, const char *password_filename, int password_length) { 135 | struct timespec T; 136 | tgl_my_clock_gettime (CLOCK_REALTIME, &T); 137 | TGLC_rand_add (&T, sizeof (T), 4.0); 138 | #ifdef HAVE_RDTSC 139 | unsigned long long r = rdtsc (); 140 | TGLC_rand_add (&r, 8, 4.0); 141 | #endif 142 | unsigned short p = getpid (); 143 | TGLC_rand_add (&p, sizeof (p), 0.0); 144 | #ifndef WIN32 145 | p = getppid (); 146 | TGLC_rand_add (&p, sizeof (p), 0.0); 147 | #endif 148 | unsigned char rb[32]; 149 | int s = get_random_bytes (TLS, rb, 32); 150 | if (s > 0) { 151 | TGLC_rand_add (rb, s, s); 152 | } 153 | memset (rb, 0, sizeof (rb)); 154 | if (password_filename && password_length > 0) { 155 | int fd = open (password_filename, O_RDONLY | O_BINARY); 156 | if (fd < 0) { 157 | vlogprintf (E_WARNING, "Warning: fail to open password file - \"%s\", %s.\n", password_filename, strerror(errno)); 158 | } else { 159 | unsigned char *a = talloc0 (password_length); 160 | int l = read (fd, a, password_length); 161 | if (l < 0) { 162 | vlogprintf (E_WARNING, "Warning: fail to read password file - \"%s\", %s.\n", password_filename, strerror(errno)); 163 | } else { 164 | vlogprintf (E_DEBUG, "read %d bytes from password file.\n", l); 165 | TGLC_rand_add (a, l, l); 166 | } 167 | close (fd); 168 | tfree_secure (a, password_length); 169 | } 170 | } 171 | TLS->TGLC_bn_ctx = TGLC_bn_ctx_new (); 172 | ensure_ptr (TLS->TGLC_bn_ctx); 173 | } 174 | 175 | int tgl_serialize_bignum (TGLC_bn *b, char *buffer, int maxlen) { 176 | int itslen = TGLC_bn_num_bytes (b); 177 | int reqlen; 178 | if (itslen < 254) { 179 | reqlen = itslen + 1; 180 | } else { 181 | reqlen = itslen + 4; 182 | } 183 | int newlen = (reqlen + 3) & -4; 184 | int pad = newlen - reqlen; 185 | reqlen = newlen; 186 | if (reqlen > maxlen) { 187 | return -reqlen; 188 | } 189 | if (itslen < 254) { 190 | *buffer++ = itslen; 191 | } else { 192 | *(int *)buffer = (itslen << 8) + 0xfe; 193 | buffer += 4; 194 | } 195 | int l = TGLC_bn_bn2bin (b, (unsigned char *)buffer); 196 | assert (l == itslen); 197 | buffer += l; 198 | while (pad --> 0) { 199 | *buffer++ = 0; 200 | } 201 | return reqlen; 202 | } 203 | 204 | 205 | long long tgl_do_compute_rsa_key_fingerprint (TGLC_rsa *key) { 206 | static char tempbuff[4096]; 207 | static unsigned char sha[20]; 208 | assert (TGLC_rsa_n (key) && TGLC_rsa_e (key)); 209 | int l1 = tgl_serialize_bignum (TGLC_rsa_n (key), tempbuff, 4096); 210 | assert (l1 > 0); 211 | int l2 = tgl_serialize_bignum (TGLC_rsa_e (key), tempbuff + l1, 4096 - l1); 212 | assert (l2 > 0 && l1 + l2 <= 4096); 213 | TGLC_sha1 ((unsigned char *)tempbuff, l1 + l2, sha); 214 | return *(long long *)(sha + 12); 215 | } 216 | 217 | void tgl_out_cstring (const char *str, long len) { 218 | assert (len >= 0 && len < (1 << 24)); 219 | assert ((char *) packet_ptr + len + 8 < (char *) (packet_buffer + PACKET_BUFFER_SIZE)); 220 | char *dest = (char *) packet_ptr; 221 | if (len < 254) { 222 | *dest++ = len; 223 | } else { 224 | *packet_ptr = (len << 8) + 0xfe; 225 | dest += 4; 226 | } 227 | memcpy (dest, str, len); 228 | dest += len; 229 | while ((long) dest & 3) { 230 | *dest++ = 0; 231 | } 232 | packet_ptr = (int *) dest; 233 | } 234 | 235 | void tgl_out_cstring_careful (const char *str, long len) { 236 | assert (len >= 0 && len < (1 << 24)); 237 | assert ((char *) packet_ptr + len + 8 < (char *) (packet_buffer + PACKET_BUFFER_SIZE)); 238 | char *dest = (char *) packet_ptr; 239 | if (len < 254) { 240 | dest++; 241 | if (dest != str) { 242 | memmove (dest, str, len); 243 | } 244 | dest[-1] = len; 245 | } else { 246 | dest += 4; 247 | if (dest != str) { 248 | memmove (dest, str, len); 249 | } 250 | *packet_ptr = (len << 8) + 0xfe; 251 | } 252 | dest += len; 253 | while ((long) dest & 3) { 254 | *dest++ = 0; 255 | } 256 | packet_ptr = (int *) dest; 257 | } 258 | 259 | 260 | void tgl_out_data (const void *data, long len) { 261 | assert (len >= 0 && len < (1 << 24) && !(len & 3)); 262 | assert ((char *) packet_ptr + len + 8 < (char *) (packet_buffer + PACKET_BUFFER_SIZE)); 263 | memcpy (packet_ptr, data, len); 264 | packet_ptr += len >> 2; 265 | } 266 | 267 | int *tgl_in_ptr, *tgl_in_end; 268 | 269 | int tgl_fetch_bignum (TGLC_bn *x) { 270 | int l = prefetch_strlen (); 271 | if (l < 0) { 272 | return l; 273 | } 274 | char *str = fetch_str (l); 275 | assert (TGLC_bn_bin2bn ((unsigned char *) str, l, x) == x); 276 | return l; 277 | } 278 | 279 | int tgl_pad_rsa_encrypt (struct tgl_state *TLS, char *from, int from_len, char *to, int size, TGLC_bn *N, TGLC_bn *E) { 280 | int pad = (255000 - from_len - 32) % 255 + 32; 281 | int chunks = (from_len + pad) / 255; 282 | int bits = TGLC_bn_num_bits (N); 283 | assert (bits >= 2041 && bits <= 2048); 284 | assert (from_len > 0 && from_len <= 2550); 285 | assert (size >= chunks * 256); 286 | assert (TGLC_rand_pseudo_bytes ((unsigned char *) from + from_len, pad) >= 0); 287 | int i; 288 | TGLC_bn *x = TGLC_bn_new (); 289 | TGLC_bn *y = TGLC_bn_new (); 290 | assert(x); 291 | assert(y); 292 | rsa_encrypted_chunks += chunks; 293 | for (i = 0; i < chunks; i++) { 294 | TGLC_bn_bin2bn ((unsigned char *) from, 255, x); 295 | assert (TGLC_bn_mod_exp (y, x, E, N, TLS->TGLC_bn_ctx) == 1); 296 | unsigned l = 256 - TGLC_bn_num_bytes (y); 297 | assert (l <= 256); 298 | memset (to, 0, l); 299 | TGLC_bn_bn2bin (y, (unsigned char *) to + l); 300 | to += 256; 301 | } 302 | TGLC_bn_free (x); 303 | TGLC_bn_free (y); 304 | return chunks * 256; 305 | } 306 | 307 | int tgl_pad_rsa_decrypt (struct tgl_state *TLS, char *from, int from_len, char *to, int size, TGLC_bn *N, TGLC_bn *D) { 308 | if (from_len < 0 || from_len > 0x1000 || (from_len & 0xff)) { 309 | return -1; 310 | } 311 | int chunks = (from_len >> 8); 312 | int bits = TGLC_bn_num_bits (N); 313 | assert (bits >= 2041 && bits <= 2048); 314 | assert (size >= chunks * 255); 315 | int i; 316 | TGLC_bn *x = TGLC_bn_new (); 317 | TGLC_bn *y = TGLC_bn_new (); 318 | assert(x); 319 | assert(y); 320 | for (i = 0; i < chunks; i++) { 321 | ++rsa_decrypted_chunks; 322 | TGLC_bn_bin2bn ((unsigned char *) from, 256, x); 323 | assert (TGLC_bn_mod_exp (y, x, D, N, TLS->TGLC_bn_ctx) == 1); 324 | int l = TGLC_bn_num_bytes (y); 325 | if (l > 255) { 326 | TGLC_bn_free (x); 327 | TGLC_bn_free (y); 328 | return -1; 329 | } 330 | assert (l >= 0 && l <= 255); 331 | memset (to, 0, 255 - l); 332 | TGLC_bn_bn2bin (y, (unsigned char *) to + 255 - l); 333 | to += 255; 334 | } 335 | TGLC_bn_free (x); 336 | TGLC_bn_free (y); 337 | return chunks * 255; 338 | } 339 | 340 | static unsigned char aes_key_raw[32], aes_iv[32]; 341 | static TGLC_aes_key aes_key; 342 | 343 | void tgl_init_aes_unauth (const char server_nonce[16], const char hidden_client_nonce[32], int encrypt) { 344 | static unsigned char buffer[64], hash[20]; 345 | memcpy (buffer, hidden_client_nonce, 32); 346 | memcpy (buffer + 32, server_nonce, 16); 347 | TGLC_sha1 (buffer, 48, aes_key_raw); 348 | memcpy (buffer + 32, hidden_client_nonce, 32); 349 | TGLC_sha1 (buffer, 64, aes_iv + 8); 350 | memcpy (buffer, server_nonce, 16); 351 | memcpy (buffer + 16, hidden_client_nonce, 32); 352 | TGLC_sha1 (buffer, 48, hash); 353 | memcpy (aes_key_raw + 20, hash, 12); 354 | memcpy (aes_iv, hash + 12, 8); 355 | memcpy (aes_iv + 28, hidden_client_nonce, 4); 356 | if (encrypt) { 357 | TGLC_aes_set_encrypt_key (aes_key_raw, 32*8, &aes_key); 358 | } else { 359 | TGLC_aes_set_decrypt_key (aes_key_raw, 32*8, &aes_key); 360 | } 361 | memset (aes_key_raw, 0, sizeof (aes_key_raw)); 362 | } 363 | 364 | void tgl_init_aes_auth (char auth_key[192], char msg_key[16], int encrypt) { 365 | static unsigned char buffer[48], hash[20]; 366 | // sha1_a = SHA1 (msg_key + substr (auth_key, 0, 32)); 367 | // sha1_b = SHA1 (substr (auth_key, 32, 16) + msg_key + substr (auth_key, 48, 16)); 368 | // sha1_с = SHA1 (substr (auth_key, 64, 32) + msg_key); 369 | // sha1_d = SHA1 (msg_key + substr (auth_key, 96, 32)); 370 | // aes_key = substr (sha1_a, 0, 8) + substr (sha1_b, 8, 12) + substr (sha1_c, 4, 12); 371 | // aes_iv = substr (sha1_a, 8, 12) + substr (sha1_b, 0, 8) + substr (sha1_c, 16, 4) + substr (sha1_d, 0, 8); 372 | memcpy (buffer, msg_key, 16); 373 | memcpy (buffer + 16, auth_key, 32); 374 | TGLC_sha1 (buffer, 48, hash); 375 | memcpy (aes_key_raw, hash, 8); 376 | memcpy (aes_iv, hash + 8, 12); 377 | 378 | memcpy (buffer, auth_key + 32, 16); 379 | memcpy (buffer + 16, msg_key, 16); 380 | memcpy (buffer + 32, auth_key + 48, 16); 381 | TGLC_sha1 (buffer, 48, hash); 382 | memcpy (aes_key_raw + 8, hash + 8, 12); 383 | memcpy (aes_iv + 12, hash, 8); 384 | 385 | memcpy (buffer, auth_key + 64, 32); 386 | memcpy (buffer + 32, msg_key, 16); 387 | TGLC_sha1 (buffer, 48, hash); 388 | memcpy (aes_key_raw + 20, hash + 4, 12); 389 | memcpy (aes_iv + 20, hash + 16, 4); 390 | 391 | memcpy (buffer, msg_key, 16); 392 | memcpy (buffer + 16, auth_key + 96, 32); 393 | TGLC_sha1 (buffer, 48, hash); 394 | memcpy (aes_iv + 24, hash, 8); 395 | 396 | if (encrypt) { 397 | TGLC_aes_set_encrypt_key (aes_key_raw, 32*8, &aes_key); 398 | } else { 399 | TGLC_aes_set_decrypt_key (aes_key_raw, 32*8, &aes_key); 400 | } 401 | memset (aes_key_raw, 0, sizeof (aes_key_raw)); 402 | } 403 | 404 | int tgl_pad_aes_encrypt (char *from, int from_len, char *to, int size) { 405 | int padded_size = (from_len + 15) & -16; 406 | assert (from_len > 0 && padded_size <= size); 407 | if (from_len < padded_size) { 408 | assert (TGLC_rand_pseudo_bytes ((unsigned char *) from + from_len, padded_size - from_len) >= 0); 409 | } 410 | TGLC_aes_ige_encrypt ((unsigned char *) from, (unsigned char *) to, padded_size, &aes_key, aes_iv, 1); 411 | return padded_size; 412 | } 413 | 414 | int tgl_pad_aes_decrypt (char *from, int from_len, char *to, int size) { 415 | if (from_len <= 0 || from_len > size || (from_len & 15)) { 416 | return -1; 417 | } 418 | TGLC_aes_ige_encrypt ((unsigned char *) from, (unsigned char *) to, from_len, &aes_key, aes_iv, 0); 419 | return from_len; 420 | } 421 | -------------------------------------------------------------------------------- /mtproto-common.h: -------------------------------------------------------------------------------- 1 | /* 2 | This file is part of tgl-library 3 | 4 | This library is free software; you can redistribute it and/or 5 | modify it under the terms of the GNU Lesser General Public 6 | License as published by the Free Software Foundation; either 7 | version 2.1 of the License, or (at your option) any later version. 8 | 9 | This library is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 | Lesser General Public License for more details. 13 | 14 | You should have received a copy of the GNU Lesser General Public 15 | License along with this library; if not, write to the Free Software 16 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 17 | 18 | Copyright Nikolay Durov, Andrey Lopatin 2012-2013 19 | Vitaly Valtman 2013-2015 20 | */ 21 | #ifndef __MTPROTO_COMMON_H__ 22 | #define __MTPROTO_COMMON_H__ 23 | 24 | #include 25 | #include "crypto/rsa_pem.h" 26 | #include "crypto/bn.h" 27 | #include 28 | #include 29 | 30 | 31 | #if defined(_MSC_VER) || defined(__MINGW32__) 32 | #define INT64_PRINTF_MODIFIER "I64" 33 | #else 34 | #define INT64_PRINTF_MODIFIER "ll" 35 | #endif 36 | 37 | //#include "interface.h" 38 | #include "tools.h" 39 | #include "auto/constants.h" 40 | 41 | #include "tgl.h" 42 | #include "tgl-inner.h" 43 | /* DH key exchange protocol data structures */ 44 | #define CODE_req_pq 0x60469778 45 | #define CODE_resPQ 0x05162463 46 | #define CODE_req_DH_params 0xd712e4be 47 | #define CODE_p_q_inner_data 0x83c95aec 48 | #define CODE_p_q_inner_data_temp 0x3c6a84d4 49 | #define CODE_server_DH_inner_data 0xb5890dba 50 | #define CODE_server_DH_params_fail 0x79cb045d 51 | #define CODE_server_DH_params_ok 0xd0e8075c 52 | #define CODE_set_client_DH_params 0xf5045f1f 53 | #define CODE_client_DH_inner_data 0x6643b654 54 | #define CODE_dh_gen_ok 0x3bcbf734 55 | #define CODE_dh_gen_retry 0x46dc1fb9 56 | #define CODE_dh_gen_fail 0xa69dae02 57 | 58 | #define CODE_bind_auth_key_inner 0x75a3f765 59 | 60 | /* service messages */ 61 | #define CODE_rpc_result 0xf35c6d01 62 | #define CODE_rpc_error 0x2144ca19 63 | #define CODE_msg_container 0x73f1f8dc 64 | #define CODE_msg_copy 0xe06046b2 65 | #define CODE_msgs_ack 0x62d6b459 66 | #define CODE_bad_msg_notification 0xa7eff811 67 | #define CODE_bad_server_salt 0xedab447b 68 | #define CODE_msgs_state_req 0xda69fb52 69 | #define CODE_msgs_state_info 0x04deb57d 70 | #define CODE_msgs_all_info 0x8cc0d131 71 | #define CODE_new_session_created 0x9ec20908 72 | #define CODE_msg_resend_req 0x7d861a08 73 | #define CODE_ping 0x7abe77ec 74 | #define CODE_pong 0x347773c5 75 | #define CODE_destroy_session 0xe7512126 76 | #define CODE_destroy_session_ok 0xe22045fc 77 | #define CODE_destroy_session_none 0x62d350c9 78 | #define CODE_destroy_sessions 0x9a6face8 79 | #define CODE_destroy_sessions_res 0xa8164668 80 | #define CODE_get_future_salts 0xb921bd04 81 | #define CODE_future_salt 0x0949d9dc 82 | #define CODE_future_salts 0xae500895 83 | #define CODE_rpc_drop_answer 0x58e4a740 84 | #define CODE_rpc_answer_unknown 0x5e2ad36e 85 | #define CODE_rpc_answer_dropped_running 0xcd78e586 86 | #define CODE_rpc_answer_dropped 0xa43ad8b7 87 | #define CODE_msg_detailed_info 0x276d3ec6 88 | #define CODE_msg_new_detailed_info 0x809db6df 89 | #define CODE_ping_delay_disconnect 0xf3427b8c 90 | #define CODE_gzip_packed 0x3072cfa1 91 | 92 | #define CODE_input_peer_notify_settings_old 0x3cf4b1be 93 | #define CODE_peer_notify_settings_old 0xddbcd4a5 94 | #define CODE_user_profile_photo_old 0x990d1493 95 | #define CODE_config_old 0x232d5905 96 | 97 | #define CODE_msg_new_detailed_info 0x809db6df 98 | 99 | #define CODE_msg_detailed_info 0x276d3ec6 100 | /* not really a limit, for struct encrypted_message only */ 101 | // #define MAX_MESSAGE_INTS 16384 102 | #define MAX_MESSAGE_INTS 1048576 103 | #define MAX_PROTO_MESSAGE_INTS 1048576 104 | 105 | #define PACKET_BUFFER_SIZE (16384 * 100 + 16) // temp fix 106 | #pragma pack(push,4) 107 | struct encrypted_message { 108 | // unencrypted header 109 | long long auth_key_id; 110 | char msg_key[16]; 111 | // encrypted part, starts with encrypted header 112 | long long server_salt; 113 | long long session_id; 114 | // long long auth_key_id2; // removed 115 | // first message follows 116 | long long msg_id; 117 | int seq_no; 118 | int msg_len; // divisible by 4 119 | int message[MAX_MESSAGE_INTS]; 120 | }; 121 | 122 | #pragma pack(pop) 123 | 124 | //TGLC_bn_ctx *bn_ctx; 125 | 126 | void tgl_prng_seed (struct tgl_state *TLS, const char *password_filename, int password_length); 127 | int tgl_serialize_bignum (TGLC_bn *b, char *buffer, int maxlen); 128 | long long tgl_do_compute_rsa_key_fingerprint (TGLC_rsa *key); 129 | 130 | #define packet_buffer tgl_packet_buffer 131 | #define packet_ptr tgl_packet_ptr 132 | 133 | extern int *tgl_packet_buffer; 134 | extern int *tgl_packet_ptr; 135 | 136 | static inline void out_ints (const int *what, int len) { 137 | assert (packet_ptr + len <= packet_buffer + PACKET_BUFFER_SIZE); 138 | memcpy (packet_ptr, what, len * 4); 139 | packet_ptr += len; 140 | } 141 | 142 | 143 | static inline void out_int (int x) { 144 | assert (packet_ptr + 1 <= packet_buffer + PACKET_BUFFER_SIZE); 145 | *packet_ptr++ = x; 146 | } 147 | 148 | 149 | static inline void out_long (long long x) { 150 | assert (packet_ptr + 2 <= packet_buffer + PACKET_BUFFER_SIZE); 151 | *(long long *)packet_ptr = x; 152 | packet_ptr += 2; 153 | } 154 | 155 | static inline void out_double (double x) { 156 | assert (packet_ptr + 2 <= packet_buffer + PACKET_BUFFER_SIZE); 157 | *(double *)packet_ptr = x; 158 | packet_ptr += 2; 159 | } 160 | 161 | static inline void clear_packet (void) { 162 | packet_ptr = packet_buffer; 163 | } 164 | 165 | void tgl_out_cstring (const char *str, long len); 166 | void tgl_out_cstring_careful (const char *str, long len); 167 | void tgl_out_data (const void *data, long len); 168 | 169 | #define out_cstring tgl_out_cstring 170 | #define out_cstring_careful tgl_out_cstring_careful 171 | #define out_data tgl_out_data 172 | 173 | static inline void out_string (const char *str) { 174 | out_cstring (str, strlen (str)); 175 | } 176 | 177 | static inline void out_bignum (TGLC_bn *n) { 178 | int l = tgl_serialize_bignum (n, (char *)packet_ptr, (PACKET_BUFFER_SIZE - (packet_ptr - packet_buffer)) * 4); 179 | assert (l > 0); 180 | packet_ptr += l >> 2; 181 | } 182 | 183 | #define in_ptr tgl_in_ptr 184 | #define in_end tgl_in_end 185 | extern int *tgl_in_ptr, *tgl_in_end; 186 | 187 | 188 | //void fetch_pts (void); 189 | //void fetch_qts (void); 190 | //void fetch_date (void); 191 | //void fetch_seq (void); 192 | static inline int prefetch_strlen (void) { 193 | if (in_ptr >= in_end) { 194 | return -1; 195 | } 196 | unsigned l = *in_ptr; 197 | if ((l & 0xff) < 0xfe) { 198 | l &= 0xff; 199 | return (in_end >= in_ptr + (l >> 2) + 1) ? (int)l : -1; 200 | } else if ((l & 0xff) == 0xfe) { 201 | l >>= 8; 202 | return (l >= 254 && in_end >= in_ptr + ((l + 7) >> 2)) ? (int)l : -1; 203 | } else { 204 | return -1; 205 | } 206 | } 207 | 208 | static inline char *fetch_str (int len) { 209 | assert (len >= 0); 210 | if (len < 254) { 211 | char *str = (char *) in_ptr + 1; 212 | in_ptr += 1 + (len >> 2); 213 | return str; 214 | } else { 215 | char *str = (char *) in_ptr + 4; 216 | in_ptr += (len + 7) >> 2; 217 | return str; 218 | } 219 | } 220 | 221 | static inline char *fetch_str_dup (void) { 222 | int l = prefetch_strlen (); 223 | assert (l >= 0); 224 | int i; 225 | char *s = fetch_str (l); 226 | for (i = 0; i < l; i++) { 227 | if (!s[i]) { break; } 228 | } 229 | char *r = talloc (i + 1); 230 | memcpy (r, s, i); 231 | r[i] = 0; 232 | return r; 233 | } 234 | 235 | static inline int fetch_update_str (char **s) { 236 | if (!*s) { 237 | *s = fetch_str_dup (); 238 | return 1; 239 | } 240 | int l = prefetch_strlen (); 241 | char *r = fetch_str (l); 242 | if (memcmp (*s, r, l) || (*s)[l]) { 243 | tfree_str (*s); 244 | *s = talloc (l + 1); 245 | memcpy (*s, r, l); 246 | (*s)[l] = 0; 247 | return 1; 248 | } 249 | return 0; 250 | } 251 | 252 | static inline int fetch_update_int (int *value) { 253 | if (*value == *in_ptr) { 254 | in_ptr ++; 255 | return 0; 256 | } else { 257 | *value = *(in_ptr ++); 258 | return 1; 259 | } 260 | } 261 | 262 | static inline int fetch_update_long (long long *value) { 263 | if (*value == *(long long *)in_ptr) { 264 | in_ptr += 2; 265 | return 0; 266 | } else { 267 | *value = *(long long *)(in_ptr); 268 | in_ptr += 2; 269 | return 1; 270 | } 271 | } 272 | 273 | static inline int set_update_int (int *value, int new_value) { 274 | if (*value == new_value) { 275 | return 0; 276 | } else { 277 | *value = new_value; 278 | return 1; 279 | } 280 | } 281 | 282 | static inline void fetch_skip (int n) { 283 | in_ptr += n; 284 | assert (in_ptr <= in_end); 285 | } 286 | 287 | static inline void fetch_skip_str (void) { 288 | int l = prefetch_strlen (); 289 | assert (l >= 0); 290 | fetch_str (l); 291 | } 292 | 293 | static inline long have_prefetch_ints (void) { 294 | return in_end - in_ptr; 295 | } 296 | 297 | int tgl_fetch_bignum (TGLC_bn *x); 298 | #define fetch_bignum tgl_fetch_bignum 299 | 300 | static inline int fetch_int (void) { 301 | assert (in_ptr + 1 <= in_end); 302 | return *(in_ptr ++); 303 | } 304 | 305 | static inline int fetch_bool (void) { 306 | assert (in_ptr + 1 <= in_end); 307 | assert (*(in_ptr) == (int)CODE_bool_true || *(in_ptr) == (int)CODE_bool_false); 308 | return *(in_ptr ++) == (int)CODE_bool_true; 309 | } 310 | 311 | static inline int prefetch_int (void) { 312 | assert (in_ptr < in_end); 313 | return *(in_ptr); 314 | } 315 | 316 | static inline void prefetch_data (void *data, int size) { 317 | assert (in_ptr + (size >> 2) <= in_end); 318 | memcpy (data, in_ptr, size); 319 | } 320 | 321 | static inline void fetch_data (void *data, int size) { 322 | assert (in_ptr + (size >> 2) <= in_end); 323 | memcpy (data, in_ptr, size); 324 | assert (!(size & 3)); 325 | in_ptr += (size >> 2); 326 | } 327 | 328 | static inline long long fetch_long (void) { 329 | assert (in_ptr + 2 <= in_end); 330 | long long r = *(long long *)in_ptr; 331 | in_ptr += 2; 332 | return r; 333 | } 334 | 335 | static inline double fetch_double (void) { 336 | assert (in_ptr + 2 <= in_end); 337 | double r = *(double *)in_ptr; 338 | in_ptr += 2; 339 | return r; 340 | } 341 | 342 | static inline void fetch_ints (void *data, int count) { 343 | assert (in_ptr + count <= in_end); 344 | memcpy (data, in_ptr, 4 * count); 345 | in_ptr += count; 346 | } 347 | 348 | static inline void fetch256 (void *buf) { 349 | int l = prefetch_strlen (); 350 | assert (l >= 0); 351 | char *s = fetch_str (l); 352 | if (l < 256) { 353 | memcpy (buf + 256 - l, s, l); 354 | memset (buf, 0, 256 - l); 355 | } else { 356 | memcpy (buf, s + (l - 256), 256); 357 | } 358 | } 359 | 360 | static inline int in_remaining (void) { 361 | return 4 * (in_end - in_ptr); 362 | } 363 | 364 | //int get_random_bytes (unsigned char *buf, int n); 365 | 366 | int tgl_pad_rsa_encrypt (struct tgl_state *TLS, char *from, int from_len, char *to, int size, TGLC_bn *N, TGLC_bn *E); 367 | int tgl_pad_rsa_decrypt (struct tgl_state *TLS, char *from, int from_len, char *to, int size, TGLC_bn *N, TGLC_bn *D); 368 | 369 | //extern long long rsa_encrypted_chunks, rsa_decrypted_chunks; 370 | 371 | //extern unsigned char aes_key_raw[32], aes_iv[32]; 372 | //extern TGLC_aes_key aes_key; 373 | 374 | void tgl_init_aes_unauth (const char server_nonce[16], const char hidden_client_nonce[32], int encrypt); 375 | void tgl_init_aes_auth (char auth_key[192], char msg_key[16], int encrypt); 376 | int tgl_pad_aes_encrypt (char *from, int from_len, char *to, int size); 377 | int tgl_pad_aes_decrypt (char *from, int from_len, char *to, int size); 378 | /* 379 | static inline void hexdump_in (void) { 380 | hexdump (in_ptr, in_end); 381 | } 382 | 383 | static inline void hexdump_out (void) { 384 | hexdump (packet_buffer, packet_ptr); 385 | }*/ 386 | 387 | #ifndef CLOCK_REALTIME 388 | #define CLOCK_REALTIME 0 389 | #define CLOCK_MONOTONIC 1 390 | #endif 391 | #endif 392 | -------------------------------------------------------------------------------- /mtproto-key.c: -------------------------------------------------------------------------------- 1 | /* 2 | This file is part of tgl-library 3 | 4 | This library is free software; you can redistribute it and/or 5 | modify it under the terms of the GNU Lesser General Public 6 | License as published by the Free Software Foundation; either 7 | version 2.1 of the License, or (at your option) any later version. 8 | 9 | This library is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 | Lesser General Public License for more details. 13 | 14 | You should have received a copy of the GNU Lesser General Public 15 | License along with this library; if not, write to the Free Software 16 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 17 | 18 | Copyright Vitaly Valtman 2015 19 | */ 20 | 21 | const unsigned char _mtproto_default_key[] = { 22 | 0xc1, 0x50, 0x02, 0x3e, 0x2f, 0x70, 0xdb, 0x79, 0x85, 0xde, 0xd0, 0x64, 23 | 0x75, 0x9c, 0xfe, 0xcf, 0x0a, 0xf3, 0x28, 0xe6, 0x9a, 0x41, 0xda, 0xf4, 24 | 0xd6, 0xf0, 0x1b, 0x53, 0x81, 0x35, 0xa6, 0xf9, 0x1f, 0x8f, 0x8b, 0x2a, 25 | 0x0e, 0xc9, 0xba, 0x97, 0x20, 0xce, 0x35, 0x2e, 0xfc, 0xf6, 0xc5, 0x68, 26 | 0x0f, 0xfc, 0x42, 0x4b, 0xd6, 0x34, 0x86, 0x49, 0x02, 0xde, 0x0b, 0x4b, 27 | 0xd6, 0xd4, 0x9f, 0x4e, 0x58, 0x02, 0x30, 0xe3, 0xae, 0x97, 0xd9, 0x5c, 28 | 0x8b, 0x19, 0x44, 0x2b, 0x3c, 0x0a, 0x10, 0xd8, 0xf5, 0x63, 0x3f, 0xec, 29 | 0xed, 0xd6, 0x92, 0x6a, 0x7f, 0x6d, 0xab, 0x0d, 0xdb, 0x7d, 0x45, 0x7f, 30 | 0x9e, 0xa8, 0x1b, 0x84, 0x65, 0xfc, 0xd6, 0xff, 0xfe, 0xed, 0x11, 0x40, 31 | 0x11, 0xdf, 0x91, 0xc0, 0x59, 0xca, 0xed, 0xaf, 0x97, 0x62, 0x5f, 0x6c, 32 | 0x96, 0xec, 0xc7, 0x47, 0x25, 0x55, 0x69, 0x34, 0xef, 0x78, 0x1d, 0x86, 33 | 0x6b, 0x34, 0xf0, 0x11, 0xfc, 0xe4, 0xd8, 0x35, 0xa0, 0x90, 0x19, 0x6e, 34 | 0x9a, 0x5f, 0x0e, 0x44, 0x49, 0xaf, 0x7e, 0xb6, 0x97, 0xdd, 0xb9, 0x07, 35 | 0x64, 0x94, 0xca, 0x5f, 0x81, 0x10, 0x4a, 0x30, 0x5b, 0x6d, 0xd2, 0x76, 36 | 0x65, 0x72, 0x2c, 0x46, 0xb6, 0x0e, 0x5d, 0xf6, 0x80, 0xfb, 0x16, 0xb2, 37 | 0x10, 0x60, 0x7e, 0xf2, 0x17, 0x65, 0x2e, 0x60, 0x23, 0x6c, 0x25, 0x5f, 38 | 0x6a, 0x28, 0x31, 0x5f, 0x40, 0x83, 0xa9, 0x67, 0x91, 0xd7, 0x21, 0x4b, 39 | 0xf6, 0x4c, 0x1d, 0xf4, 0xfd, 0x0d, 0xb1, 0x94, 0x4f, 0xb2, 0x6a, 0x2a, 40 | 0x57, 0x03, 0x1b, 0x32, 0xee, 0xe6, 0x4a, 0xd1, 0x5a, 0x8b, 0xa6, 0x88, 41 | 0x85, 0xcd, 0xe7, 0x4a, 0x5b, 0xfc, 0x92, 0x0f, 0x6a, 0xbf, 0x59, 0xba, 42 | 0x5c, 0x75, 0x50, 0x63, 0x73, 0xe7, 0x13, 0x0f, 0x90, 0x42, 0xda, 0x92, 43 | 0x21, 0x79, 0x25, 0x1f 44 | }; 45 | const unsigned int _mtproto_default_key_len = 256; 46 | const long long _mtproto_default_e = 65537; 47 | 48 | const unsigned char *tglmp_get_default_key (void) { 49 | return _mtproto_default_key; 50 | } 51 | unsigned int tglmp_get_default_key_len (void) { 52 | return _mtproto_default_key_len; 53 | } 54 | long long tglmp_get_default_e (void) { 55 | return _mtproto_default_e; 56 | } 57 | -------------------------------------------------------------------------------- /mtproto-key.h: -------------------------------------------------------------------------------- 1 | /* 2 | This file is part of tgl-library 3 | 4 | This library is free software; you can redistribute it and/or 5 | modify it under the terms of the GNU Lesser General Public 6 | License as published by the Free Software Foundation; either 7 | version 2.1 of the License, or (at your option) any later version. 8 | 9 | This library is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 | Lesser General Public License for more details. 13 | 14 | You should have received a copy of the GNU Lesser General Public 15 | License along with this library; if not, write to the Free Software 16 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 17 | 18 | Copyright Vitaly Valtman 2015 19 | */ 20 | 21 | #ifndef __MTPROTO_KEY_H__ 22 | #define __MTPROTO_KEY_H__ 23 | 24 | const unsigned char *tglmp_get_default_key (void); 25 | unsigned int tglmp_get_default_key_len (void); 26 | long long tglmp_get_default_e (void); 27 | 28 | #endif 29 | -------------------------------------------------------------------------------- /mtproto-utils.c: -------------------------------------------------------------------------------- 1 | #include "config.h" 2 | #include "crypto/bn.h" 3 | #include "tl-parser/portable_endian.h" 4 | #include "tgl.h" 5 | #include "tools.h" 6 | #include "mtproto-utils.h" 7 | 8 | static unsigned long long gcd (unsigned long long a, unsigned long long b) { 9 | return b ? gcd (b, a % b) : a; 10 | } 11 | 12 | static int check_prime (struct tgl_state *TLS, TGLC_bn *p) { 13 | int r = TGLC_bn_is_prime (p, /* "use default" */ 0, 0, TLS->TGLC_bn_ctx, 0); 14 | ensure (r >= 0); 15 | return r; 16 | } 17 | 18 | 19 | // Complete set of checks see at https://core.telegram.org/mtproto/security_guidelines 20 | 21 | 22 | // Checks that (p,g) is acceptable pair for DH 23 | int tglmp_check_DH_params (struct tgl_state *TLS, TGLC_bn *p, int g) { 24 | if (g < 2 || g > 7) { return -1; } 25 | if (TGLC_bn_num_bits (p) != 2048) { return -1; } 26 | 27 | TGLC_bn *t = TGLC_bn_new (); 28 | 29 | TGLC_bn *dh_g = TGLC_bn_new (); 30 | 31 | ensure (TGLC_bn_set_word (dh_g, 4 * g)); 32 | ensure (TGLC_bn_mod (t, p, dh_g, TLS->TGLC_bn_ctx)); 33 | int x = TGLC_bn_get_word (t); 34 | assert (x >= 0 && x < 4 * g); 35 | 36 | TGLC_bn_free (dh_g); 37 | 38 | int res = 0; 39 | switch (g) { 40 | case 2: 41 | if (x != 7) { res = -1; } 42 | break; 43 | case 3: 44 | if (x % 3 != 2) { res = -1; } 45 | break; 46 | case 4: 47 | break; 48 | case 5: 49 | if (x % 5 != 1 && x % 5 != 4) { res = -1; } 50 | break; 51 | case 6: 52 | if (x != 19 && x != 23) { res = -1; } 53 | break; 54 | case 7: 55 | if (x % 7 != 3 && x % 7 != 5 && x % 7 != 6) { res = -1; } 56 | break; 57 | } 58 | 59 | if (res < 0 || !check_prime (TLS, p)) { 60 | TGLC_bn_free (t); 61 | return -1; 62 | } 63 | 64 | TGLC_bn *b = TGLC_bn_new (); 65 | ensure (TGLC_bn_set_word (b, 2)); 66 | ensure (TGLC_bn_div (t, 0, p, b, TLS->TGLC_bn_ctx)); 67 | if (!check_prime (TLS, t)) { 68 | res = -1; 69 | } 70 | TGLC_bn_free (b); 71 | TGLC_bn_free (t); 72 | return res; 73 | } 74 | 75 | // checks that g_a is acceptable for DH 76 | int tglmp_check_g_a (struct tgl_state *TLS, TGLC_bn *p, TGLC_bn *g_a) { 77 | if (TGLC_bn_num_bytes (g_a) > 256) { 78 | return -1; 79 | } 80 | if (TGLC_bn_num_bits (g_a) < 2048 - 64) { 81 | return -1; 82 | } 83 | if (TGLC_bn_cmp (p, g_a) <= 0) { 84 | return -1; 85 | } 86 | 87 | TGLC_bn *dif = TGLC_bn_new (); 88 | TGLC_bn_sub (dif, p, g_a); 89 | if (TGLC_bn_num_bits (dif) < 2048 - 64) { 90 | TGLC_bn_free (dif); 91 | return -1; 92 | } 93 | TGLC_bn_free (dif); 94 | return 0; 95 | } 96 | 97 | static unsigned long long BN2ull (TGLC_bn *b) { 98 | if (sizeof (unsigned long) == 8) { 99 | return TGLC_bn_get_word (b); 100 | } else if (sizeof (unsigned long long) == 8) { 101 | assert (0); // As long as nobody ever uses this code, assume it is broken. 102 | unsigned long long tmp; 103 | /* Here be dragons, but it should be okay due to be64toh */ 104 | TGLC_bn_bn2bin (b, (unsigned char *) &tmp); 105 | return be64toh (tmp); 106 | } else { 107 | assert (0); 108 | } 109 | } 110 | 111 | static void ull2BN (TGLC_bn *b, unsigned long long val) { 112 | if (sizeof (unsigned long) == 8 || val < (1ll << 32)) { 113 | TGLC_bn_set_word (b, val); 114 | } else if (sizeof (unsigned long long) == 8) { 115 | assert (0); // As long as nobody ever uses this code, assume it is broken. 116 | htobe64(val); 117 | /* Here be dragons, but it should be okay due to htobe64 */ 118 | TGLC_bn_bin2bn ((unsigned char *) &val, 8, b); 119 | } else { 120 | assert (0); 121 | } 122 | } 123 | 124 | int bn_factorize (TGLC_bn *pq, TGLC_bn *p, TGLC_bn *q) { 125 | // Should work in any case 126 | // Rewrite this code 127 | unsigned long long what = BN2ull (pq); 128 | 129 | int it = 0; 130 | 131 | unsigned long long g = 0; 132 | int i; 133 | for (i = 0; i < 3 || it < 1000; i++) { 134 | int q = ((rand() & 15) + 17) % what; 135 | unsigned long long x = (long long)rand () % (what - 1) + 1, y = x; 136 | int lim = 1 << (i + 18); 137 | int j; 138 | for (j = 1; j < lim; j++) { 139 | ++it; 140 | unsigned long long a = x, b = x, c = q; 141 | while (b) { 142 | if (b & 1) { 143 | c += a; 144 | if (c >= what) { 145 | c -= what; 146 | } 147 | } 148 | a += a; 149 | if (a >= what) { 150 | a -= what; 151 | } 152 | b >>= 1; 153 | } 154 | x = c; 155 | unsigned long long z = x < y ? what + x - y : x - y; 156 | g = gcd (z, what); 157 | if (g != 1) { 158 | break; 159 | } 160 | if (!(j & (j - 1))) { 161 | y = x; 162 | } 163 | } 164 | if (g > 1 && g < what) break; 165 | } 166 | 167 | assert (g > 1 && g < what); 168 | unsigned long long p1 = g; 169 | unsigned long long p2 = what / g; 170 | if (p1 > p2) { 171 | unsigned long long t = p1; p1 = p2; p2 = t; 172 | } 173 | ull2BN (p, p1); 174 | ull2BN (q, p2); 175 | return 0; 176 | } 177 | -------------------------------------------------------------------------------- /mtproto-utils.h: -------------------------------------------------------------------------------- 1 | #ifndef __MTPROTO_UTILS_H__ 2 | #define __MTPROTO_UTILS_H__ 3 | #include "crypto/bn.h" 4 | int tglmp_check_DH_params (struct tgl_state *TLS, TGLC_bn *p, int g); 5 | int tglmp_check_g_a (struct tgl_state *TLS, TGLC_bn *p, TGLC_bn *g_a); 6 | int bn_factorize (TGLC_bn *pq, TGLC_bn *p, TGLC_bn *q); 7 | #endif 8 | -------------------------------------------------------------------------------- /mtproto.tl: -------------------------------------------------------------------------------- 1 | ---types--- 2 | resPQ#05162463 nonce:int128 server_nonce:int128 pq:string server_public_key_fingerprints:(Vector long) = ResPQ; 3 | server_DH_params_fail#79cb045d nonce:int128 server_nonce:int128 new_nonce_hash:int128 = Server_DH_Params; 4 | server_DH_params_ok#d0e8075c nonce:int128 server_nonce:int128 encrypted_answer:string = Server_DH_Params; 5 | 6 | p_q_inner_data#83c95aec pq:string p:string q:string nonce:int128 server_nonce:int128 new_nonce:int256 = P_Q_inner_data; 7 | p_q_inner_data_temp#3c6a84d4 pq:string p:string q:string nonce:int128 server_nonce:int128 new_nonce:int256 expires_in:int = P_Q_inner_data; 8 | client_DH_inner_data#6643b654 nonce:int128 server_nonce:int128 retry_id:long g_b:string = Client_DH_Inner_Data; 9 | 10 | dh_gen_ok#3bcbf734 nonce:int128 server_nonce:int128 new_nonce_hash1:int128 = Set_client_DH_params_answer; 11 | dh_gen_retry#46dc1fb9 nonce:int128 server_nonce:int128 new_nonce_hash2:int128 = Set_client_DH_params_answer; 12 | dh_gen_fail#a69dae02 nonce:int128 server_nonce:int128 new_nonce_hash3:int128 = Set_client_DH_params_answer; 13 | 14 | server_DH_inner_data#b5890dba nonce:int128 server_nonce:int128 g:int dh_prime:string g_a:string server_time:int = Server_DH_inner_data; 15 | 16 | ---functions--- 17 | req_pq#60469778 nonce:int128 = ResPQ; 18 | req_DH_params#d712e4be nonce:int128 server_nonce:int128 p:string q:string public_key_fingerprint:long encrypted_data:string = Server_DH_Params; 19 | set_client_DH_params#f5045f1f nonce:int128 server_nonce:int128 encrypted_data:string = Set_client_DH_params_answer; 20 | -------------------------------------------------------------------------------- /no-preview.h: -------------------------------------------------------------------------------- 1 | /* 2 | This file is part of tgl-library 3 | 4 | This library is free software; you can redistribute it and/or 5 | modify it under the terms of the GNU Lesser General Public 6 | License as published by the Free Software Foundation; either 7 | version 2.1 of the License, or (at your option) any later version. 8 | 9 | This library is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 | Lesser General Public License for more details. 13 | 14 | You should have received a copy of the GNU Lesser General Public 15 | License along with this library; if not, write to the Free Software 16 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 17 | 18 | Copyright Vitaly Valtman 2013-2015 19 | */ 20 | 21 | // Just sample jpg file 90x90 22 | 23 | int thumb_file_size = (82 * 6 - 2) * 4; 24 | int thumb_file [] = { 25 | 0xe0ffd8ff, 0x464a1000, 0x01004649, 0x64000101, 0x00006400, 0xa002e2ff, 26 | 0x5f434349, 0x464f5250, 0x00454c49, 0x00000101, 0x636c9002, 0x3004736d, 27 | 0x6e6d0000, 0x47527274, 0x59582042, 0xdd07205a, 0x04000b00, 0x1b001600, 28 | 0x63612400, 0x50417073, 0x00004c50, 0x00000000, 0x00000000, 0x00000000, 29 | 0x00000000, 0x00000000, 0x00000000, 0x0100d6f6, 0x00000000, 0x636c2dd3, 30 | 0x0000736d, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 31 | 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 32 | 0x65640b00, 0x00006373, 0x00000801, 0x70633800, 0x00007472, 0x00004001, 33 | 0x74774e00, 0x00007470, 0x00009001, 0x68631400, 0x00006461, 0x0000a401, 34 | 0x58722c00, 0x00005a59, 0x0000d001, 0x58621400, 0x00005a59, 0x0000e401, 35 | 0x58671400, 0x00005a59, 0x0000f801, 0x54721400, 0x00004352, 0x00000c02, 36 | 0x54672000, 0x00004352, 0x00002c02, 0x54622000, 0x00004352, 0x00004c02, 37 | 0x68632000, 0x00006d72, 0x00006c02, 0x6c6d2400, 0x00006375, 0x00000000, 38 | 0x00000100, 0x6e650c00, 0x00005355, 0x00001c00, 0x73001c00, 0x47005200, 39 | 0x20004200, 0x75006200, 0x6c006900, 0x2d007400, 0x6e006900, 0x6c6d0000, 40 | 0x00006375, 0x00000000, 0x00000100, 0x6e650c00, 0x00005355, 0x00003200, 41 | 0x4e001c00, 0x20006f00, 0x6f006300, 0x79007000, 0x69007200, 0x68006700, 42 | 0x2c007400, 0x75002000, 0x65007300, 0x66002000, 0x65007200, 0x6c006500, 43 | 0x00007900, 0x59580000, 0x0000205a, 0x00000000, 0x0100d6f6, 0x00000000, 44 | 0x66732dd3, 0x00003233, 0x01000000, 0x00004a0c, 0xffffe305, 0x00002af3, 45 | 0x00009b07, 0xffff87fd, 0xffffa2fb, 0x0000a3fd, 0x0000d803, 0x595894c0, 46 | 0x0000205a, 0x00000000, 0x0000946f, 0x0000ee38, 0x59589003, 0x0000205a, 47 | 0x00000000, 0x00009d24, 0x0000830f, 0x5958beb6, 0x0000205a, 0x00000000, 48 | 0x0000a562, 0x000090b7, 0x6170de18, 0x00006172, 0x03000000, 0x02000000, 49 | 0x00006666, 0x0000a7f2, 0x0000590d, 0x0000d013, 0x61705b0a, 0x00006172, 50 | 0x03000000, 0x02000000, 0x00006666, 0x0000a7f2, 0x0000590d, 0x0000d013, 51 | 0x61705b0a, 0x00006172, 0x03000000, 0x02000000, 0x00006666, 0x0000a7f2, 52 | 0x0000590d, 0x0000d013, 0x68635b0a, 0x00006d72, 0x03000000, 0x00000000, 53 | 0x0000d7a3, 0x00007b54, 0x0000cd4c, 0x00009a99, 0x00006626, 0xdbff5c0f, 54 | 0x14004300, 0x0f120f0e, 0x1112140d, 0x14161712, 0x21331f18, 0x1f1c1c1f, 55 | 0x252f2d3f, 0x4e414a33, 0x4841494d, 0x765c5246, 0x6f575264, 0x66484658, 56 | 0x7a6f688c, 0x8485847d, 0x9b91634f, 0x769a808f, 0xff7f8481, 0x014300db, 57 | 0x1f171716, 0x213c1f1b, 0x547f3c21, 0x7f7f5448, 0x7f7f7f7f, 0x7f7f7f7f, 58 | 0x7f7f7f7f, 0x7f7f7f7f, 0x7f7f7f7f, 0x7f7f7f7f, 0x7f7f7f7f, 0x7f7f7f7f, 59 | 0x7f7f7f7f, 0x7f7f7f7f, 0x7f7f7f7f, 0x7f7f7f7f, 0x1100c0ff, 0x005a0008, 60 | 0x2201035a, 0x01110200, 0xff011103, 0x001900c4, 0x01010101, 0x00000101, 61 | 0x00000000, 0x00000000, 0x02030400, 0xc4ff0605, 0x00103600, 0x02010401, 62 | 0x06050304, 0x00000306, 0x01000000, 0x11030200, 0x05211204, 0x13514131, 63 | 0x32146122, 0x23918171, 0x72423424, 0x432515a1, 0xa2827444, 0xc4fff0b3, 64 | 0x01011400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x1400c4ff, 65 | 0x00000111, 0x00000000, 0x00000000, 0x00000000, 0xdaff0000, 0x01030c00, 66 | 0x03110200, 0x003f0011, 0x404434fb, 0xbcb4875c, 0x006b38b0, 0x03dcdb12, 67 | 0xf4637f74, 0xe519f153, 0x09d7c5c7, 0x47d29160, 0x20692f18, 0xd06d786a, 68 | 0x53f7f922, 0x17b3e260, 0x2fe8668c, 0x1786a473, 0x9775efbd, 0xe917e43a, 69 | 0x1d0a1bb0, 0x114d0f82, 0x14651110, 0x35f299ed, 0xe9b09680, 0xf5a4fc2f, 70 | 0xe975bd03, 0xb506737b, 0x04444440, 0x5c444044, 0x8e8dedbd, 0xc61adc7b, 71 | 0x689c738b, 0x92a0dc01, 0x58e2b77f, 0x7bfb37d1, 0xb5b5e79d, 0xdbf968cc, 72 | 0xead3f48d, 0x38ed1313, 0xdea77c86, 0xae089963, 0xc743435a, 0x403fe4ce, 73 | 0x392ee1b9, 0xed39e718, 0xd6517e2d, 0x7fc4aa03, 0xb7ad7590, 0x77e7e6ab, 74 | 0x34bf705d, 0x7c77ca53, 0x3dea1299, 0x7fb0bcf4, 0x241fadc5, 0x95a7a816, 75 | 0x13fbe6f3, 0x3182b135, 0xd1b4b224, 0x1b0d48a2, 0xbf9d26d8, 0x82dc3640, 76 | 0x63569a2a, 0xbbd224c3, 0xb9b4714c, 0x1680aec6, 0x3d311856, 0x9b59be91, 77 | 0x09876ca6, 0x61d86564, 0x5a9f06d2, 0x36f51b0d, 0x8682e476, 0xacb1b131, 78 | 0xd1584363, 0x00456b4d, 0x22d2053b, 0x22202202, 0xf3f30222, 0xe3e513e5, 79 | 0xf1e6e1f0, 0x2380496e, 0x5fdcdb68, 0x549b3a27, 0x825e6a6c, 0x6522028b, 80 | 0xaf91ccc8, 0x341cf26b, 0x58dbc4b5, 0xf2289add, 0x0854ddbd, 0x0b9247d5, 81 | 0xf02b5c54, 0x3f917f92, 0xaf56affd, 0xe3760637, 0x05cebde0, 0xed4c76ce, 82 | 0x3cef1b63, 0x7fd8aff8, 0xa0c902ea, 0x7e730d0a, 0x435834f3, 0x26edbb76, 83 | 0xd3ec00fd, 0x76d48efa, 0xa8560f2d, 0x0e766331, 0xd319993c, 0x20243209, 84 | 0x61b7e6c8, 0x998331d0, 0x640ee802, 0x47a3d493, 0xfab99413, 0x4fd871f1, 85 | 0xe9443792, 0x627e051c, 0xd8f3051c, 0x2f28f558, 0x64b51745, 0x1b2bfee3, 86 | 0xb8783953, 0x9900fff6, 0xd8176a65, 0x5a3bf56a, 0x1b331fdb, 0x64b3572f, 87 | 0xd59a3643, 0xaf3abce1, 0x11dd20bd, 0x01111110, 0x5c141011, 0xb3e3083f, 88 | 0xd9b19cc4, 0x17edb20e, 0xa78e9aa1, 0x4ef4de06, 0x00c0bfe7, 0x7e1e442d, 89 | 0x9221fe38, 0xedb5c7dc, 0x6338078a, 0x62495b8d, 0xc11d9b8c, 0x49e81b16, 90 | 0x51d02bea, 0x3eb86d70, 0xc8bc4f13, 0xa10ec758, 0xd40751c0, 0x5ac94710, 91 | 0xc4c8b080, 0x95492b83, 0x975ee696, 0xb7bd96b4, 0x17379cce, 0x82e856e8, 92 | 0xe4c2c82a, 0x398e935f, 0x632437ea, 0x7c9c87d2, 0xdc1ddb7c, 0x65a80a48, 93 | 0x2309f164, 0x51fab475, 0x081dc11d, 0xda45573b, 0x6622f3f3, 0x48f1b214, 94 | 0x676c4edb, 0x243468c7, 0x00ffde60, 0xf1630350, 0xa0076c1d, 0x8f2c0c8b, 95 | 0x2383c26b, 0x361a8f4e, 0xaceea6c9, 0x01dd5a5d, 0x11111011, 0xc3780c04, 96 | 0xbf093ee2, 0xc7972c0b, 0x00d99040, 0xc0c20eb7, 0x659d3bd4, 0x269ab85e, 97 | 0x468e114f, 0x11ad4fdb, 0x83d083d8, 0x8c52f4bd, 0x3c9664bf, 0xa4f9c77c, 98 | 0x22a68876, 0xadb18784, 0xf480be83, 0x885a00ea, 0x220e0a88, 0xc303e4f6, 99 | 0xc866e058, 0xdddbd661, 0xdf395db1, 0xbad64343, 0xe6e65b03, 0x668e81c3, 100 | 0xad619e98, 0xeeb94563, 0xd4d19a3c, 0x3316ce95, 0x9d65f1e1, 0x3bf324fe, 101 | 0x0e468f53, 0xc386068c, 0xa89e24f7, 0xf0c7c73b, 0xb60e391f, 0x1b8827cb, 102 | 0x58601954, 0xc54f90f9, 0x80886ec5, 0x88088888, 0x1b7bb980, 0xb4c71c23, 103 | 0xe6148e39, 0xb12358b8, 0xbd08225d, 0x0ffef085, 0x72b4f025, 0x635ce389, 104 | 0xb90277e4, 0x0d05e000, 0x9bf9dbb9, 0x8e749fbc, 0x7ee6abbf, 0x4ddbf4af, 105 | 0x728df7f3, 0x10b59adf, 0xe3c38f49, 0xb23c638a, 0xdb3d9349, 0x66899a64, 106 | 0x00004dd5, 0xf51b5adf, 0x2220a255, 0xd9ff0f22}; 107 | -------------------------------------------------------------------------------- /queries.h: -------------------------------------------------------------------------------- 1 | /* 2 | This file is part of tgl-library 3 | 4 | This library is free software; you can redistribute it and/or 5 | modify it under the terms of the GNU Lesser General Public 6 | License as published by the Free Software Foundation; either 7 | version 2.1 of the License, or (at your option) any later version. 8 | 9 | This library is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 | Lesser General Public License for more details. 13 | 14 | You should have received a copy of the GNU Lesser General Public 15 | License along with this library; if not, write to the Free Software 16 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 17 | 18 | Copyright Vitaly Valtman 2013-2015 19 | */ 20 | //#include "net.h" 21 | #ifndef __QUERIES_H__ 22 | #define __QUERIES_H__ 23 | #include "tgl-structures.h" 24 | #include "auto.h" 25 | #include "tgl-layout.h" 26 | 27 | #define QUERY_ACK_RECEIVED 1 28 | #define QUERY_FORCE_SEND 2 29 | 30 | struct query; 31 | struct query_methods { 32 | int (*on_answer)(struct tgl_state *TLS, struct query *q, void *DS); 33 | int (*on_error)(struct tgl_state *TLS, struct query *q, int error_code, int len, const char *error); 34 | int (*on_timeout)(struct tgl_state *TLS, struct query *q); 35 | struct paramed_type *type; 36 | char *name; 37 | double timeout; 38 | }; 39 | 40 | struct query { 41 | long long msg_id; 42 | int data_len; 43 | int flags; 44 | int seq_no; 45 | long long session_id; 46 | void *data; 47 | struct query_methods *methods; 48 | struct tgl_timer *ev; 49 | struct tgl_dc *DC; 50 | struct tgl_session *session; 51 | struct paramed_type *type; 52 | void *extra; 53 | void *callback; 54 | void *callback_extra; 55 | }; 56 | 57 | 58 | struct query *tglq_send_query (struct tgl_state *TLS, struct tgl_dc *DC, int len, void *data, struct query_methods *methods, void *extra, void *callback, void *callback_extra); 59 | void tglq_query_ack (struct tgl_state *TLS, long long id); 60 | int tglq_query_error (struct tgl_state *TLS, long long id); 61 | int tglq_query_result (struct tgl_state *TLS, long long id); 62 | void tglq_query_restart (struct tgl_state *TLS, long long id); 63 | 64 | //double next_timer_in (void); 65 | //void work_timers (void); 66 | 67 | //extern struct query_methods help_get_config_methods; 68 | 69 | double get_double_time (void); 70 | 71 | void tgl_do_send_bind_temp_key (struct tgl_state *TLS, struct tgl_dc *D, long long nonce, int expires_at, void *data, int len, long long msg_id); 72 | 73 | void tgl_do_request_exchange (struct tgl_state *TLS, struct tgl_secret_chat *E); 74 | void tgl_do_confirm_exchange (struct tgl_state *TLS, struct tgl_secret_chat *E, int sen_nop); 75 | void tgl_do_accept_exchange (struct tgl_state *TLS, struct tgl_secret_chat *E, long long exchange_id, unsigned char g_a[]); 76 | void tgl_do_commit_exchange (struct tgl_state *TLS, struct tgl_secret_chat *E, unsigned char g_a[]); 77 | void tgl_do_abort_exchange (struct tgl_state *TLS, struct tgl_secret_chat *E); 78 | 79 | void tglq_regen_query (struct tgl_state *TLS, long long id); 80 | void tglq_query_delete (struct tgl_state *TLS, long long id); 81 | void tglq_query_free_all (struct tgl_state *TLS); 82 | void tglq_regen_queries_from_old_session (struct tgl_state *TLS, struct tgl_dc *DC, struct tgl_session *S); 83 | // For binlog 84 | 85 | //int get_dh_config_on_answer (struct query *q); 86 | //void fetch_dc_option (void); 87 | #endif 88 | -------------------------------------------------------------------------------- /tg-mime-types.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #define MAX_MIME_TYPES_NUM 10000 4 | 5 | #include "mime-types.c" 6 | 7 | static int mime_initialized; 8 | static int mime_type_number; 9 | static char *mime_type_names[MAX_MIME_TYPES_NUM]; 10 | static char *mime_type_extensions[MAX_MIME_TYPES_NUM]; 11 | 12 | static void mime_init (void) { 13 | char *start = (char *)mime_types; 14 | char *end = start + mime_types_len; 15 | mime_initialized = 1; 16 | char *c = start; 17 | while (c < end) { 18 | if (*c == '#') { 19 | while (c < end && *c != '\n') { 20 | c ++; 21 | } 22 | if (c < end) { 23 | c ++; 24 | } 25 | } else { 26 | while (*c <= ' ' && *c != '\n' && c < end) { 27 | c ++; 28 | } 29 | assert (*c > ' ' && *c != '\n' && c < end); 30 | char *name = c; 31 | while (*c > ' ' && *c != '\n' && c < end) { 32 | c ++; 33 | } 34 | assert (*c <= ' ' && *c != '\n' && c < end); 35 | *c = 0; 36 | c ++; 37 | while (1) { 38 | while (*c <= ' ' && *c != '\n' && c < end) { 39 | c ++; 40 | } 41 | if (*c == '\n' || c == end) { 42 | if (*c == '\n') { c ++; } 43 | break; 44 | } 45 | char *ext = c; 46 | while (*c > ' ' && *c != '\n' && c < end) { 47 | c ++; 48 | } 49 | assert (c != end); 50 | int br = (*c == '\n'); 51 | *c = 0; 52 | c ++; 53 | assert (mime_type_number < MAX_MIME_TYPES_NUM); 54 | mime_type_names[mime_type_number] = name; 55 | mime_type_extensions[mime_type_number] = ext; 56 | mime_type_number ++; 57 | if (br) { break; } 58 | } 59 | } 60 | } 61 | } 62 | 63 | char *tg_extension_by_mime (const char *mime_type) { 64 | if (!mime_initialized) { 65 | mime_init (); 66 | } 67 | int i; 68 | for (i = 0; i < mime_type_number; i++) { 69 | if (!strcmp (mime_type_names[i], mime_type)) { 70 | return mime_type_extensions[i]; 71 | } 72 | } 73 | return NULL; 74 | } 75 | 76 | char *tg_mime_by_filename (const char *filename) { 77 | int l = strlen (filename); 78 | const char *p = filename - 1 + l; 79 | while (p >= filename && *p != '.') { 80 | p --; 81 | } 82 | p ++; 83 | 84 | if (!mime_initialized) { 85 | mime_init (); 86 | } 87 | 88 | static char *def = "application/octet-stream"; 89 | if (strlen (p) > 10) { 90 | return def; 91 | } 92 | static char s[11]; 93 | strcpy (s, p); 94 | char *q = s; 95 | while (*q) { 96 | if (*q >= 'A' && *p <= 'Z') { 97 | *q = *q + 'z' - 'Z'; 98 | } 99 | q ++; 100 | } 101 | int i; 102 | for (i = 0; i < mime_type_number; i++) { 103 | if (!strcmp (mime_type_extensions[i], s)) { 104 | return mime_type_names[i]; 105 | } 106 | } 107 | return def; 108 | } 109 | -------------------------------------------------------------------------------- /tg-mime-types.h: -------------------------------------------------------------------------------- 1 | char *tg_mime_by_filename (const char *filename); 2 | char *tg_extension_by_mime (const char *mime_type); 3 | 4 | -------------------------------------------------------------------------------- /tgl-binlog.h: -------------------------------------------------------------------------------- 1 | /* 2 | This file is part of tgl-library 3 | 4 | This library is free software; you can redistribute it and/or 5 | modify it under the terms of the GNU Lesser General Public 6 | License as published by the Free Software Foundation; either 7 | version 2.1 of the License, or (at your option) any later version. 8 | 9 | This library is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 | Lesser General Public License for more details. 13 | 14 | You should have received a copy of the GNU Lesser General Public 15 | License along with this library; if not, write to the Free Software 16 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 17 | 18 | Copyright Vitaly Valtman 2013-2015 19 | */ 20 | #ifndef __BINLOG_H__ 21 | #define __BINLOG_H__ 22 | 23 | //#include "structures.h" 24 | #include "tgl.h" 25 | #include "auto/auto-types.h" 26 | 27 | #ifdef __cplusplus 28 | extern "C" { 29 | #endif 30 | 31 | void bl_do_dc_option (struct tgl_state *TLS, int flags, int id, const char *name, int l1, const char *ip, int l2, int port); 32 | 33 | void bl_do_set_working_dc (struct tgl_state *TLS, int num); 34 | void bl_do_dc_signed (struct tgl_state *TLS, int id); 35 | void bl_do_set_our_id (struct tgl_state *TLS, tgl_peer_id_t id); 36 | void bl_do_set_dh_params (struct tgl_state *TLS, int root, unsigned char prime[], int version); 37 | 38 | void bl_do_set_pts (struct tgl_state *TLS, int pts); 39 | void bl_do_set_qts (struct tgl_state *TLS, int qts); 40 | void bl_do_set_date (struct tgl_state *TLS, int date); 41 | void bl_do_set_seq (struct tgl_state *TLS, int seq); 42 | void bl_do_set_channel_pts (struct tgl_state *TLS, int id, int pts); 43 | 44 | void bl_do_set_auth_key (struct tgl_state *TLS, int num, unsigned char *buf); 45 | 46 | void bl_do_set_msg_id (struct tgl_state *TLS, struct tgl_message_id *old_id, struct tgl_message_id *new_id); 47 | void bl_do_message_delete (struct tgl_state *TLS, struct tgl_message_id *id); 48 | 49 | void bl_do_peer_delete (struct tgl_state *TLS, tgl_peer_id_t id); 50 | 51 | void bl_do_chat_add_user (struct tgl_state *TLS, tgl_peer_id_t id, int version, int user, int inviter, int date); 52 | void bl_do_chat_del_user (struct tgl_state *TLS, tgl_peer_id_t id, int version, int user); 53 | 54 | void bl_do_msg_update (struct tgl_state *TLS, struct tgl_message_id *id); 55 | void bl_do_reset_authorization (struct tgl_state *TLS); 56 | 57 | 58 | void bl_do_edit_message (struct tgl_state *TLS, struct tgl_message_id *id, tgl_peer_id_t *from_id, tgl_peer_id_t *to_id, tgl_peer_id_t *fwd_from_id, int *fwd_date, int *date, const char *message, int message_len, struct tl_ds_message_media *media, struct tl_ds_message_action *action, int *reply_id, struct tl_ds_reply_markup *reply_markup, struct tl_ds_vector *entities, int flags); 59 | void bl_do_edit_message_encr (struct tgl_state *TLS, struct tgl_message_id *id, tgl_peer_id_t *from_id, tgl_peer_id_t *to_id, int *date, const char *message, int message_len, struct tl_ds_decrypted_message_media *media, struct tl_ds_decrypted_message_action *action, struct tl_ds_encrypted_file *file, int flags); 60 | void bl_do_encr_chat_exchange (struct tgl_state *TLS, tgl_peer_id_t id, long long *exchange_id, const void *key, int *state); 61 | void bl_do_user (struct tgl_state *TLS, int id, long long *access_hash, const char *first_name, int first_name_len, const char *last_name, int last_name_len, const char *phone, int phone_len, const char *username, int username_len, struct tl_ds_photo *photo, struct tl_ds_user_profile_photo *profile_photo, int *last_read_in, int *last_read_out, struct tl_ds_bot_info *bot_info, int flags); 62 | void bl_do_chat (struct tgl_state *TLS, int id, const char *title, int title_len, int *user_num, int *date, int *version, struct tl_ds_vector *participants, struct tl_ds_chat_photo *chat_photo, struct tl_ds_photo *photo, int *admin, int *last_read_in, int *last_read_out, int flags); 63 | void bl_do_encr_chat (struct tgl_state *TLS, int id, long long *access_hash, int *date, int *admin, int *user_id, void *key, void *g_key, void *first_key_id, int *state, int *ttl, int *layer, int *in_seq_no, int *last_in_seq_no, int *out_seq_no, long long *key_fingerprint, int flags, const char *print_name, int print_name_len); 64 | void bl_do_channel (struct tgl_state *TLS, int id, long long *access_hash, int *date, const char *title, int title_len, const char *username, int username_len, struct tl_ds_chat_photo *chat_photo, struct tl_ds_photo *photo, int *version, char *about, int about_len, int *participants_count, int *admins_count, int *kicked_count, int *last_read_in, int flags); 65 | void bl_do_peer_delete (struct tgl_state *TLS, tgl_peer_id_t id); 66 | 67 | #ifdef __cplusplus 68 | } 69 | #endif 70 | 71 | #endif 72 | -------------------------------------------------------------------------------- /tgl-fetch.h: -------------------------------------------------------------------------------- 1 | /* 2 | This file is part of tgl-library 3 | 4 | This library is free software; you can redistribute it and/or 5 | modify it under the terms of the GNU Lesser General Public 6 | License as published by the Free Software Foundation; either 7 | version 2.1 of the License, or (at your option) any later version. 8 | 9 | This library is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 | Lesser General Public License for more details. 13 | 14 | You should have received a copy of the GNU Lesser General Public 15 | License along with this library; if not, write to the Free Software 16 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 17 | 18 | Copyright Vitaly Valtman 2014-2015 19 | */ 20 | #ifndef __TGL_FETCH_H__ 21 | #define __TGL_FETCH_H__ 22 | #include "tgl.h" 23 | #include "auto/auto-types.h" 24 | 25 | struct tgl_user *tglf_fetch_alloc_user (struct tgl_state *TLS, struct tl_ds_user *DS_U); 26 | struct tgl_user *tglf_fetch_alloc_user_full (struct tgl_state *TLS, struct tl_ds_user_full *DS_U); 27 | struct tgl_chat *tglf_fetch_alloc_chat (struct tgl_state *TLS, struct tl_ds_chat *DS_C); 28 | struct tgl_chat *tglf_fetch_alloc_chat_full (struct tgl_state *TLS, struct tl_ds_messages_chat_full *DS_MCF); 29 | struct tgl_channel *tglf_fetch_alloc_channel (struct tgl_state *TLS, struct tl_ds_chat *DS_C); 30 | struct tgl_channel *tglf_fetch_alloc_channel_full (struct tgl_state *TLS, struct tl_ds_messages_chat_full *DS_MCF); 31 | struct tgl_secret_chat *tglf_fetch_alloc_encrypted_chat (struct tgl_state *TLS, struct tl_ds_encrypted_chat *DS_EC); 32 | struct tgl_message *tglf_fetch_alloc_message (struct tgl_state *TLS, struct tl_ds_message *DS_M, int *new_msg); 33 | struct tgl_message *tglf_fetch_alloc_message_short_buf (struct tgl_state *TLS); 34 | struct tgl_message *tglf_fetch_alloc_message_short_chat_buf (struct tgl_state *TLS); 35 | struct tgl_message *tglf_fetch_alloc_encrypted_message (struct tgl_state *TLS, struct tl_ds_encrypted_message *DS_EM); 36 | tgl_peer_id_t tglf_fetch_peer_id (struct tgl_state *TLS, struct tl_ds_peer *DS_P); 37 | long long tglf_fetch_user_photo (struct tgl_state *TLS, struct tgl_user *U, struct tl_ds_user_profile_photo *DS_UPP); 38 | 39 | void tglf_fetch_message_media (struct tgl_state *TLS, struct tgl_message_media *M, struct tl_ds_message_media *DS_MM); 40 | void tglf_fetch_message_action (struct tgl_state *TLS, struct tgl_message_action *M, struct tl_ds_message_action *DS_MA); 41 | //void tglf_fetch_chat_full (struct tgl_state *TLS, struct tgl_chat *C); 42 | 43 | void tglf_fetch_encrypted_message_file (struct tgl_state *TLS, struct tgl_message_media *M, struct tl_ds_encrypted_file *DS_EF); 44 | void tglf_fetch_message_media_encrypted (struct tgl_state *TLS, struct tgl_message_media *M, struct tl_ds_decrypted_message_media *DS_DMM); 45 | void tglf_fetch_message_action_encrypted (struct tgl_state *TLS, struct tgl_message_action *M, struct tl_ds_decrypted_message_action *DS_DMA); 46 | int tglf_fetch_user_status (struct tgl_state *TLS, struct tgl_user_status *S, struct tgl_user *U, struct tl_ds_user_status *DS_US); 47 | enum tgl_typing_status tglf_fetch_typing (struct tl_ds_send_message_action *DS_SMA); 48 | void tglf_fetch_chat_participants (struct tgl_state *TLS, struct tgl_chat *C, struct tl_ds_chat_participants *DS_CP); 49 | void tglf_fetch_int_array (int *dst, struct tl_ds_vector *src, int len); 50 | void tglf_fetch_int_tuple (int *dst, int **src, int len); 51 | int tglf_fetch_file_location (struct tgl_state *TLS, struct tgl_file_location *loc, struct tl_ds_file_location *DS_FL); 52 | 53 | void tglf_fetch_message_short (struct tgl_state *TLS, struct tgl_message *M, struct tl_ds_updates *DS_U); 54 | void tglf_fetch_message_short_chat (struct tgl_state *TLS, struct tgl_message *M, struct tl_ds_updates *DS_U); 55 | 56 | struct tgl_message *tglf_fetch_alloc_message_short (struct tgl_state *TLS, struct tl_ds_updates *DS_U); 57 | struct tgl_message *tglf_fetch_alloc_message_short_chat (struct tgl_state *TLS, struct tl_ds_updates *DS_U); 58 | struct tgl_photo *tglf_fetch_alloc_photo (struct tgl_state *TLS, struct tl_ds_photo *DS_P); 59 | struct tgl_bot_info *tglf_fetch_alloc_bot_info (struct tgl_state *TLS, struct tl_ds_bot_info *DS_BI); 60 | struct tgl_message_reply_markup *tglf_fetch_alloc_reply_markup (struct tgl_state *TLS, struct tgl_message *M, struct tl_ds_reply_markup *DS_RM); 61 | void tglf_fetch_message_entities (struct tgl_state *TLS, struct tgl_message *M, struct tl_ds_vector *DS); 62 | #endif 63 | -------------------------------------------------------------------------------- /tgl-inner.h: -------------------------------------------------------------------------------- 1 | /* 2 | This file is part of tgl-library 3 | 4 | This library is free software; you can redistribute it and/or 5 | modify it under the terms of the GNU Lesser General Public 6 | License as published by the Free Software Foundation; either 7 | version 2.1 of the License, or (at your option) any later version. 8 | 9 | This library is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 | Lesser General Public License for more details. 13 | 14 | You should have received a copy of the GNU Lesser General Public 15 | License along with this library; if not, write to the Free Software 16 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 17 | 18 | Copyright Vitaly Valtman 2014-2015 19 | */ 20 | 21 | #ifndef __TGL_INNER_H__ 22 | #define __TGL_INNER_H__ 23 | 24 | #ifndef vlogprintf 25 | #define vlogprintf(verbosity_level,...) \ 26 | do { \ 27 | if (TLS->verbosity >= verbosity_level) { \ 28 | TLS->callback.logprintf (__VA_ARGS__); \ 29 | } \ 30 | } while (0) 31 | #endif 32 | 33 | #endif 34 | -------------------------------------------------------------------------------- /tgl-methods-in.h: -------------------------------------------------------------------------------- 1 | // normally you should not use these methods 2 | // use them with caution 3 | 4 | 5 | #ifndef __TGL_METHODS_IN_H__ 6 | #define __TGL_METHODS_IN_H__ 7 | 8 | /* {{{ AUTHORIZATION METHODS. NORMALLY YOU DON'T NEED THEM */ 9 | 10 | // send query to updated DCs' ips 11 | // automatically renews data on update 12 | void tgl_do_help_get_config (struct tgl_state *TLS, void (*callback)(struct tgl_state *TLS, void *callback_extra, int success), void *callback_extra); 13 | 14 | // requests server to send code to specified phone number 15 | // if user is logged in elsewhere message will first appear as telegram message 16 | // and SMS will be sent some time after 17 | void tgl_do_send_code (struct tgl_state *TLS, const char *phone, int phone_len, void (*callback)(struct tgl_state *TLS, void *callback_extra, int success, int registered, const char *hash), void *callback_extra); 18 | 19 | // request server to send code via phone call 20 | void tgl_do_phone_call (struct tgl_state *TLS, const char *phone, int phone_len, const char *hash, int hash_len, void (*callback)(struct tgl_state *TLS, void *callback_extra, int success), void *callback_extra); 21 | 22 | // sends code from SMS to server. This step should end authorization, unless user have password 23 | int tgl_do_send_code_result (struct tgl_state *TLS, const char *phone, int phone_len, const char *hash, int hash_len, const char *code, int code_len, void (*callback)(struct tgl_state *TLS, void *callback_extra, int success, struct tgl_user *Self), void *callback_extra); 24 | 25 | 26 | // sends code from SMS, username and lastname to server. This step should end new user registration 27 | int tgl_do_send_code_result_auth (struct tgl_state *TLS, const char *phone, int phone_len, const char *hash, int hash_len, const char *code, int code_len, const char *first_name, int first_name_len, const char *last_name, int last_name_len, void (*callback)(struct tgl_state *TLS, void *callback_extra, int success, struct tgl_user *Self), void *callback_extra); 28 | 29 | /* }}} */ 30 | 31 | void tgl_do_send_msg (struct tgl_state *TLS, struct tgl_message *M, void (*callback)(struct tgl_state *TLS, void *callback_extra, int success, struct tgl_message *M), void *callback_extra); 32 | 33 | void tgl_do_check_password (struct tgl_state *TLS, void (*callback)(struct tgl_state *TLS, void *extra, int success), void *callback_extra); 34 | 35 | void tgl_do_export_auth (struct tgl_state *TLS, int num, void (*callback) (struct tgl_state *TLS, void *callback_extra, int success), void *callback_extra); 36 | 37 | void tgl_do_create_secret_chat (struct tgl_state *TLS, tgl_peer_id_t id, void (*callback)(struct tgl_state *TLS, void *callback_extra, int success, struct tgl_secret_chat *E), void *callback_extra); 38 | 39 | void tgl_do_get_difference (struct tgl_state *TLS, int sync_from_start, void (*callback)(struct tgl_state *TLS, void *callback_extra, int success), void *callback_extra); 40 | 41 | void tgl_do_lookup_state (struct tgl_state *TLS); 42 | 43 | void tgl_do_help_get_config_dc (struct tgl_state *TLS, struct tgl_dc *D, void (*callback)(struct tgl_state *TLS, void *, int), void *callback_extra); 44 | 45 | void tgl_do_request_exchange (struct tgl_state *TLS, struct tgl_secret_chat *E); 46 | 47 | void tgl_do_create_keys_end (struct tgl_state *TLS, struct tgl_secret_chat *U); 48 | 49 | void tgl_do_send_encr_chat_layer (struct tgl_state *TLS, struct tgl_secret_chat *E); 50 | #endif 51 | -------------------------------------------------------------------------------- /tgl-net-inner.h: -------------------------------------------------------------------------------- 1 | /* 2 | This file is part of tgl-library 3 | 4 | This library is free software; you can redistribute it and/or 5 | modify it under the terms of the GNU Lesser General Public 6 | License as published by the Free Software Foundation; either 7 | version 2.1 of the License, or (at your option) any later version. 8 | 9 | This library is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 | Lesser General Public License for more details. 13 | 14 | You should have received a copy of the GNU Lesser General Public 15 | License along with this library; if not, write to the Free Software 16 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 17 | 18 | Copyright Vitaly Valtman 2013-2015 19 | */ 20 | #ifndef __NET_H__ 21 | #define __NET_H__ 22 | 23 | struct connection_buffer { 24 | unsigned char *start; 25 | unsigned char *end; 26 | unsigned char *rptr; 27 | unsigned char *wptr; 28 | struct connection_buffer *next; 29 | }; 30 | 31 | enum conn_state { 32 | conn_none, 33 | conn_connecting, 34 | conn_ready, 35 | conn_failed, 36 | conn_stopped 37 | }; 38 | 39 | struct connection { 40 | int fd; 41 | char *ip; 42 | int port; 43 | int flags; 44 | enum conn_state state; 45 | int ipv6[4]; 46 | struct connection_buffer *in_head; 47 | struct connection_buffer *in_tail; 48 | struct connection_buffer *out_head; 49 | struct connection_buffer *out_tail; 50 | int in_bytes; 51 | int out_bytes; 52 | int packet_num; 53 | int out_packet_num; 54 | int last_connect_time; 55 | int in_fail_timer; 56 | struct mtproto_methods *methods; 57 | struct tgl_state *TLS; 58 | struct tgl_session *session; 59 | struct tgl_dc *dc; 60 | void *extra; 61 | struct event *ping_ev; 62 | struct event *fail_ev; 63 | struct event *read_ev; 64 | struct event *write_ev; 65 | double last_receive_time; 66 | }; 67 | 68 | //extern struct connection *Connections[]; 69 | 70 | int tgln_write_out (struct connection *c, const void *data, int len); 71 | void tgln_flush_out (struct connection *c); 72 | int tgln_read_in (struct connection *c, void *data, int len); 73 | int tgln_read_in_lookup (struct connection *c, void *data, int len); 74 | 75 | //void tgln_insert_msg_id (struct tgl_session *S, long long id); 76 | 77 | extern struct tgl_net_methods tgl_conn_methods; 78 | 79 | //void create_all_outbound_connections (void); 80 | 81 | //struct connection *create_connection (const char *host, int port, struct tgl_session *session, struct connection_methods *methods); 82 | //struct tgl_dc *tgln_alloc_dc (int id, char *ip, int port); 83 | //void tgln_dc_create_session (struct tgl_dc *DC, struct mtproto_methods *methods); 84 | struct connection *tgln_create_connection (struct tgl_state *TLS, const char *host, int port, struct tgl_session *session, struct tgl_dc *dc, struct mtproto_methods *methods); 85 | 86 | #define GET_DC(c) (c->session->dc) 87 | #endif 88 | -------------------------------------------------------------------------------- /tgl-net.h: -------------------------------------------------------------------------------- 1 | /* 2 | This file is part of tgl-library 3 | 4 | This library is free software; you can redistribute it and/or 5 | modify it under the terms of the GNU Lesser General Public 6 | License as published by the Free Software Foundation; either 7 | version 2.1 of the License, or (at your option) any later version. 8 | 9 | This library is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 | Lesser General Public License for more details. 13 | 14 | You should have received a copy of the GNU Lesser General Public 15 | License along with this library; if not, write to the Free Software 16 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 17 | 18 | Copyright Vitaly Valtman 2013-2015 19 | */ 20 | #ifndef __NET_H__ 21 | #define __NET_H__ 22 | 23 | extern struct tgl_net_methods tgl_conn_methods; 24 | #endif 25 | -------------------------------------------------------------------------------- /tgl-structures.h: -------------------------------------------------------------------------------- 1 | /* 2 | This file is part of tgl-library 3 | 4 | This library is free software; you can redistribute it and/or 5 | modify it under the terms of the GNU Lesser General Public 6 | License as published by the Free Software Foundation; either 7 | version 2.1 of the License, or (at your option) any later version. 8 | 9 | This library is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 | Lesser General Public License for more details. 13 | 14 | You should have received a copy of the GNU Lesser General Public 15 | License along with this library; if not, write to the Free Software 16 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 17 | 18 | Copyright Vitaly Valtman 2013-2015 19 | */ 20 | #ifndef __STRUCTURES_H__ 21 | #define __STRUCTURES_H__ 22 | 23 | #include 24 | #include "tgl-layout.h" 25 | #include "tgl-fetch.h" 26 | #include "tgl.h" 27 | 28 | char *tgls_default_create_print_name (struct tgl_state *TLS, tgl_peer_id_t id, const char *a1, const char *a2, const char *a3, const char *a4); 29 | 30 | 31 | void tgls_free_user (struct tgl_state *TLS, struct tgl_user *U); 32 | void tgls_free_chat (struct tgl_state *TLS, struct tgl_chat *U); 33 | void tgls_free_photo (struct tgl_state *TLS, struct tgl_photo *P); 34 | void tgls_free_message (struct tgl_state *TLS, struct tgl_message *M); 35 | void tgls_free_bot_info (struct tgl_state *TLS, struct tgl_bot_info *B); 36 | void tgls_clear_message (struct tgl_state *TLS, struct tgl_message *M); 37 | 38 | struct tgl_message *tglm_message_alloc (struct tgl_state *TLS, tgl_message_id_t *id); 39 | void tglm_message_insert_tree (struct tgl_state *TLS, struct tgl_message *M); 40 | void tglm_update_message_id (struct tgl_state *TLS, struct tgl_message *M, long long id); 41 | void tglm_message_insert (struct tgl_state *TLS, struct tgl_message *M); 42 | void tglm_message_insert_unsent (struct tgl_state *TLS, struct tgl_message *M); 43 | void tglm_message_remove_unsent (struct tgl_state *TLS, struct tgl_message *M); 44 | void tglm_send_all_unsent (struct tgl_state *TLS); 45 | void tglm_message_remove_tree (struct tgl_state *TLS, struct tgl_message *M); 46 | void tglm_message_add_peer (struct tgl_state *TLS, struct tgl_message *M); 47 | void tglm_message_del_peer (struct tgl_state *TLS, struct tgl_message *M); 48 | void tglm_message_del_use (struct tgl_state *TLS, struct tgl_message *M); 49 | void tglm_message_add_use (struct tgl_state *TLS, struct tgl_message *M); 50 | void tglm_message_del_temp_id (struct tgl_state *TLS, struct tgl_message *M); 51 | void tglm_message_del_random_id (struct tgl_state *TLS, struct tgl_message *M); 52 | 53 | void tglp_peer_insert_name (struct tgl_state *TLS, tgl_peer_t *P); 54 | void tglp_peer_delete_name (struct tgl_state *TLS, tgl_peer_t *P); 55 | void tglp_insert_encrypted_chat (struct tgl_state *TLS, tgl_peer_t *P); 56 | void tglp_insert_user (struct tgl_state *TLS, tgl_peer_t *P); 57 | void tglp_insert_chat (struct tgl_state *TLS, tgl_peer_t *P); 58 | void tglp_insert_channel (struct tgl_state *TLS, tgl_peer_t *P); 59 | //enum tgl_typing_status tglf_fetch_typing_buf (void); 60 | void tgls_messages_mark_read (struct tgl_state *TLS, struct tgl_message *M, int out, int seq); 61 | 62 | //void tgls_insert_random2local (struct tgl_state *TLS, long long random_id, tgl_message_id_t *local_id); 63 | //void tgls_insert_temp2local (struct tgl_state *TLS, int temp_id, tgl_message_id_t *local_id); 64 | tgl_message_id_t *tgls_get_local_by_random (struct tgl_state *TLS, long long random_id); 65 | tgl_message_id_t *tgls_get_local_by_temp (struct tgl_state *TLS, int temp_id); 66 | 67 | 68 | void tgls_message_change_temp_id (struct tgl_state *TLS, struct tgl_message *M, int temp_id); 69 | void tgls_message_change_random_id (struct tgl_state *TLS, struct tgl_message *M, long long random_id); 70 | 71 | 72 | void tgl_photo_insert (struct tgl_state *TLS, struct tgl_photo *P); 73 | struct tgl_photo *tgl_photo_get (struct tgl_state *TLS, long long id); 74 | struct tgl_document *tgl_document_get (struct tgl_state *TLS, long long id); 75 | void tgl_document_insert (struct tgl_state *TLS, struct tgl_document *P); 76 | struct tgl_webpage *tgl_webpage_get (struct tgl_state *TLS, long long id); 77 | void tgl_webpage_insert (struct tgl_state *TLS, struct tgl_webpage *P); 78 | 79 | tgl_message_id_t tgl_convert_temp_msg_id (struct tgl_state *TLS, tgl_message_id_t msg_id); 80 | 81 | static inline tgl_peer_id_t tgl_msg_id_to_peer_id (tgl_message_id_t msg_id) { 82 | tgl_peer_id_t id; 83 | id.peer_type = msg_id.peer_type; 84 | id.peer_id = msg_id.peer_id; 85 | id.access_hash = msg_id.access_hash; 86 | return id; 87 | } 88 | 89 | static inline tgl_message_id_t tgl_peer_id_to_msg_id (tgl_peer_id_t peer_id, long long msg_id) { 90 | tgl_message_id_t id; 91 | id.peer_type = peer_id.peer_type; 92 | id.peer_id = peer_id.peer_id; 93 | id.access_hash = peer_id.access_hash; 94 | id.id = msg_id; 95 | return id; 96 | } 97 | 98 | static inline tgl_message_id_t tgl_peer_id_to_random_msg_id (tgl_peer_id_t peer_id) { 99 | long long id; 100 | tglt_secure_random (&id, 8); 101 | return tgl_peer_id_to_msg_id (peer_id, id); 102 | } 103 | #endif 104 | -------------------------------------------------------------------------------- /tgl-timers.c: -------------------------------------------------------------------------------- 1 | /* 2 | This file is part of tgl-library 3 | 4 | This library is free software; you can redistribute it and/or 5 | modify it under the terms of the GNU Lesser General Public 6 | License as published by the Free Software Foundation; either 7 | version 2.1 of the License, or (at your option) any later version. 8 | 9 | This library is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 | Lesser General Public License for more details. 13 | 14 | You should have received a copy of the GNU Lesser General Public 15 | License along with this library; if not, write to the Free Software 16 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 17 | 18 | Copyright Vitaly Valtman 2013-2015 19 | */ 20 | #include "config.h" 21 | #ifdef EVENT_V2 22 | #include 23 | #include 24 | #include 25 | #else 26 | #include 27 | #include "event-old.h" 28 | #endif 29 | 30 | #include "tgl.h" 31 | #include 32 | 33 | static void timer_alarm (evutil_socket_t fd, short what, void *arg) { 34 | void **p = arg; 35 | ((void (*)(struct tgl_state *, void *))p[1]) (p[0], p[2]); 36 | } 37 | 38 | struct tgl_timer *tgl_timer_alloc (struct tgl_state *TLS, void (*cb)(struct tgl_state *TLS, void *arg), void *arg) { 39 | void **p = malloc (sizeof (void *) * 3); 40 | p[0] = TLS; 41 | p[1] = cb; 42 | p[2] = arg; 43 | return (void *)evtimer_new (TLS->ev_base, timer_alarm, p); 44 | } 45 | 46 | void tgl_timer_insert (struct tgl_timer *t, double p) { 47 | if (p < 0) { p = 0; } 48 | double e = p - (int)p; 49 | if (e < 0) { e = 0; } 50 | struct timeval pv = { (int)p, (int)(e * 1e6)}; 51 | event_add ((void *)t, &pv); 52 | } 53 | 54 | void tgl_timer_delete (struct tgl_timer *t) { 55 | event_del ((void *)t); 56 | } 57 | 58 | void tgl_timer_free (struct tgl_timer *t) { 59 | void *arg = event_get_callback_arg ((void *)t); 60 | free (arg); 61 | event_free ((void *)t); 62 | } 63 | 64 | struct tgl_timer_methods tgl_libevent_timers = { 65 | .alloc = tgl_timer_alloc, 66 | .insert = tgl_timer_insert, 67 | .remove = tgl_timer_delete, 68 | .free = tgl_timer_free 69 | }; 70 | -------------------------------------------------------------------------------- /tgl-timers.h: -------------------------------------------------------------------------------- 1 | /* 2 | This file is part of tgl-library 3 | 4 | This library is free software; you can redistribute it and/or 5 | modify it under the terms of the GNU Lesser General Public 6 | License as published by the Free Software Foundation; either 7 | version 2.1 of the License, or (at your option) any later version. 8 | 9 | This library is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 | Lesser General Public License for more details. 13 | 14 | You should have received a copy of the GNU Lesser General Public 15 | License along with this library; if not, write to the Free Software 16 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 17 | 18 | Copyright Vitaly Valtman 2013-2015 19 | */ 20 | 21 | #ifndef __TGL_TIMERS_H__ 22 | #define __TGL_TIMERS_H__ 23 | 24 | #include "tgl.h" 25 | extern struct tgl_timer_methods tgl_libevent_timers; 26 | 27 | #endif 28 | -------------------------------------------------------------------------------- /tgl.c: -------------------------------------------------------------------------------- 1 | /* 2 | This file is part of tgl-library 3 | 4 | This library is free software; you can redistribute it and/or 5 | modify it under the terms of the GNU Lesser General Public 6 | License as published by the Free Software Foundation; either 7 | version 2.1 of the License, or (at your option) any later version. 8 | 9 | This library is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 | Lesser General Public License for more details. 13 | 14 | You should have received a copy of the GNU Lesser General Public 15 | License along with this library; if not, write to the Free Software 16 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 17 | 18 | Copyright Vitaly Valtman 2014-2015 19 | */ 20 | 21 | #ifdef HAVE_CONFIG_H 22 | #include "config.h" 23 | #endif 24 | 25 | #include "crypto/rsa_pem.h" 26 | #include "tgl.h" 27 | #include "tools.h" 28 | #include "mtproto-client.h" 29 | #include "tgl-structures.h" 30 | //#include "net.h" 31 | 32 | #include 33 | 34 | struct tgl_state tgl_state; 35 | 36 | 37 | void tgl_set_binlog_mode (struct tgl_state *TLS, int mode) { 38 | TLS->binlog_enabled = mode; 39 | } 40 | 41 | void tgl_set_binlog_path (struct tgl_state *TLS, const char *path) { 42 | TLS->binlog_name = tstrdup (path); 43 | } 44 | 45 | void tgl_set_auth_file_path (struct tgl_state *TLS, const char *path) { 46 | TLS->auth_file = tstrdup (path); 47 | } 48 | 49 | void tgl_set_download_directory (struct tgl_state *TLS, const char *path) { 50 | if (TLS->downloads_directory) { 51 | tfree_str (TLS->downloads_directory); 52 | } 53 | TLS->downloads_directory = tstrdup (path); 54 | } 55 | 56 | void tgl_set_callback (struct tgl_state *TLS, struct tgl_update_callback *cb) { 57 | TLS->callback = *cb; 58 | } 59 | 60 | void tgl_set_rsa_key (struct tgl_state *TLS, const char *key) { 61 | assert (TLS->rsa_key_num < TGL_MAX_RSA_KEYS_NUM); 62 | TLS->rsa_key_list[TLS->rsa_key_num ++] = tstrdup (key); 63 | } 64 | 65 | void tgl_set_rsa_key_direct (struct tgl_state *TLS, unsigned long e, int n_bytes, const unsigned char *n) { 66 | assert (TLS->rsa_key_num < TGL_MAX_RSA_KEYS_NUM); 67 | TLS->rsa_key_list[TLS->rsa_key_num] = NULL; 68 | TLS->rsa_key_loaded[TLS->rsa_key_num] = TGLC_rsa_new (e, n_bytes, n); 69 | TLS->rsa_key_num ++; 70 | } 71 | 72 | int tgl_init (struct tgl_state *TLS) { 73 | assert (TLS->timer_methods); 74 | assert (TLS->net_methods); 75 | if (!TLS->callback.create_print_name) { 76 | TLS->callback.create_print_name = tgls_default_create_print_name; 77 | } 78 | if (!TLS->temp_key_expire_time) { 79 | TLS->temp_key_expire_time = 100000; 80 | } 81 | 82 | TLS->message_list.next_use = &TLS->message_list; 83 | TLS->message_list.prev_use = &TLS->message_list; 84 | 85 | if (tglmp_on_start (TLS) < 0) { 86 | return -1; 87 | } 88 | 89 | if (!TLS->app_id) { 90 | TLS->app_id = TG_APP_ID; 91 | TLS->app_hash = tstrdup (TG_APP_HASH); 92 | } 93 | return 0; 94 | } 95 | 96 | int tgl_authorized_dc (struct tgl_state *TLS, struct tgl_dc *DC) { 97 | assert (DC); 98 | return (DC->flags & 4) != 0;//DC->auth_key_id; 99 | } 100 | 101 | int tgl_signed_dc (struct tgl_state *TLS, struct tgl_dc *DC) { 102 | assert (DC); 103 | return (DC->flags & TGLDCF_LOGGED_IN) != 0; 104 | } 105 | 106 | void tgl_register_app_id (struct tgl_state *TLS, int app_id, const char *app_hash) { 107 | TLS->app_id = app_id; 108 | TLS->app_hash = tstrdup (app_hash); 109 | } 110 | 111 | struct tgl_state *tgl_state_alloc (void) { 112 | return (struct tgl_state *)talloc0 (sizeof (struct tgl_state)); 113 | } 114 | 115 | void tgl_incr_verbosity (struct tgl_state *TLS) { 116 | TLS->verbosity ++; 117 | } 118 | 119 | void tgl_set_verbosity (struct tgl_state *TLS, int val) { 120 | TLS->verbosity = val; 121 | } 122 | 123 | void tgl_enable_pfs (struct tgl_state *TLS) { 124 | TLS->enable_pfs = 1; 125 | } 126 | 127 | void tgl_set_test_mode (struct tgl_state *TLS) { 128 | TLS->test_mode ++; 129 | } 130 | 131 | void tgl_set_net_methods (struct tgl_state *TLS, struct tgl_net_methods *methods) { 132 | TLS->net_methods = methods; 133 | } 134 | 135 | void tgl_set_timer_methods (struct tgl_state *TLS, struct tgl_timer_methods *methods) { 136 | TLS->timer_methods = methods; 137 | } 138 | 139 | void tgl_set_ev_base (struct tgl_state *TLS, void *ev_base) { 140 | TLS->ev_base = ev_base; 141 | } 142 | 143 | void tgl_set_app_version (struct tgl_state *TLS, const char *app_version) { 144 | if (TLS->app_version) { 145 | tfree_str (TLS->app_version); 146 | } 147 | TLS->app_version = tstrdup (app_version); 148 | } 149 | 150 | void tgl_enable_ipv6 (struct tgl_state *TLS) { 151 | TLS->ipv6_enabled = 1; 152 | } 153 | 154 | void tgl_disable_link_preview (struct tgl_state *TLS) { 155 | TLS->disable_link_preview = 1; 156 | } 157 | 158 | void tgl_enable_bot (struct tgl_state *TLS) { 159 | TLS->is_bot = 1; 160 | } 161 | -------------------------------------------------------------------------------- /tools.c: -------------------------------------------------------------------------------- 1 | /* 2 | This file is part of tgl-library 3 | 4 | This library is free software; you can redistribute it and/or 5 | modify it under the terms of the GNU Lesser General Public 6 | License as published by the Free Software Foundation; either 7 | version 2.1 of the License, or (at your option) any later version. 8 | 9 | This library is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 | Lesser General Public License for more details. 13 | 14 | You should have received a copy of the GNU Lesser General Public 15 | License along with this library; if not, write to the Free Software 16 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 17 | 18 | Copyright Vitaly Valtman 2013-2015 19 | */ 20 | 21 | #ifdef HAVE_CONFIG_H 22 | #include "config.h" 23 | #endif 24 | 25 | #define _GNU_SOURCE 26 | 27 | #include 28 | #include 29 | #include 30 | #include 31 | #include "crypto/rand.h" 32 | #include 33 | #include 34 | #include 35 | 36 | //#include "interface.h" 37 | #include "tools.h" 38 | 39 | #ifdef __MACH__ 40 | #include 41 | #include 42 | #endif 43 | 44 | #ifndef CLOCK_REALTIME 45 | #define CLOCK_REALTIME 0 46 | #define CLOCK_MONOTONIC 1 47 | #endif 48 | 49 | #ifdef WIN32 50 | #include 51 | #include 52 | int vasprintf(char ** __restrict__ ret, 53 | const char * __restrict__ format, 54 | va_list ap) { 55 | int len; 56 | /* Get Length */ 57 | len = _vsnprintf(NULL,0,format,ap); 58 | if (len < 0) return -1; 59 | /* +1 for \0 terminator. */ 60 | *ret = malloc(len + 1); 61 | /* Check malloc fail*/ 62 | if (!*ret) return -1; 63 | /* Write String */ 64 | _vsnprintf(*ret,len+1,format,ap); 65 | /* Terminate explicitly */ 66 | (*ret)[len] = '\0'; 67 | return len; 68 | } 69 | 70 | int clock_gettime(int ignored, struct timespec *spec) 71 | { 72 | __int64 wintime; 73 | GetSystemTimeAsFileTime((FILETIME*)&wintime); 74 | wintime -= 116444736000000000; //1jan1601 to 1jan1970 75 | spec->tv_sec = wintime / 10000000; //seconds 76 | spec->tv_nsec = wintime % 10000000 *100; //nano-seconds 77 | return 0; 78 | } 79 | #endif 80 | 81 | #ifdef VALGRIND_FIXES 82 | #include "valgrind/memcheck.h" 83 | #endif 84 | 85 | #define RES_PRE 8 86 | #define RES_AFTER 8 87 | #define MAX_BLOCKS 1000000 88 | static void *blocks[MAX_BLOCKS]; 89 | static void *free_blocks[MAX_BLOCKS]; 90 | static int used_blocks; 91 | static int free_blocks_cnt; 92 | 93 | static long long total_allocated_bytes; 94 | 95 | void logprintf (const char *format, ...) __attribute__ ((format (printf, 1, 2), weak)); 96 | void logprintf (const char *format, ...) { 97 | va_list ap; 98 | va_start (ap, format); 99 | vfprintf (stdout, format, ap); 100 | va_end (ap); 101 | } 102 | 103 | //extern int verbosity; 104 | 105 | //static long long total_allocated_bytes; 106 | 107 | int tgl_snprintf (char *buf, int len, const char *format, ...) { 108 | va_list ap; 109 | va_start (ap, format); 110 | int r = vsnprintf (buf, len, format, ap); 111 | va_end (ap); 112 | assert (r <= len && "tsnprintf buffer overflow"); 113 | return r; 114 | } 115 | 116 | int tgl_asprintf (char **res, const char *format, ...) { 117 | va_list ap; 118 | va_start (ap, format); 119 | int r = vasprintf (res, format, ap); 120 | assert (r >= 0); 121 | va_end (ap); 122 | void *rs = talloc (strlen (*res) + 1); 123 | memcpy (rs, *res, strlen (*res) + 1); 124 | free (*res); 125 | *res = rs; 126 | return r; 127 | } 128 | 129 | void tgl_free_debug (void *ptr, int size __attribute__ ((unused))) { 130 | if (!ptr) { 131 | assert (!size); 132 | return; 133 | } 134 | total_allocated_bytes -= size; 135 | ptr -= RES_PRE; 136 | if (size != (int)((*(int *)ptr) ^ 0xbedabeda)) { 137 | logprintf ("size = %d, ptr = %d\n", size, (*(int *)ptr) ^ 0xbedabeda); 138 | } 139 | assert (*(int *)ptr == (int)((size) ^ 0xbedabeda)); 140 | assert (*(int *)(ptr + RES_PRE + size) == (int)((size) ^ 0x7bed7bed)); 141 | assert (*(int *)(ptr + 4) == size); 142 | int block_num = *(int *)(ptr + 4 + RES_PRE + size); 143 | if (block_num >= used_blocks) { 144 | logprintf ("block_num = %d, used = %d\n", block_num, used_blocks); 145 | } 146 | assert (block_num < used_blocks); 147 | if (block_num < used_blocks - 1) { 148 | void *p = blocks[used_blocks - 1]; 149 | int s = (*(int *)p) ^ 0xbedabeda; 150 | *(int *)(p + 4 + RES_PRE + s) = block_num; 151 | blocks[block_num] = p; 152 | } 153 | blocks[--used_blocks] = 0; 154 | memset (ptr, 0, size + RES_PRE + RES_AFTER); 155 | *(int *)ptr = size + 12; 156 | free_blocks[free_blocks_cnt ++] = ptr; 157 | } 158 | 159 | void tgl_free_release (void *ptr, int size) { 160 | total_allocated_bytes -= size; 161 | memset (ptr, 0, size); 162 | free (ptr); 163 | } 164 | 165 | 166 | 167 | void *tgl_realloc_debug (void *ptr, size_t old_size __attribute__ ((unused)), size_t size) { 168 | void *p = talloc (size); 169 | memcpy (p, ptr, size >= old_size ? old_size : size); 170 | if (ptr) { 171 | tfree (ptr, old_size); 172 | } else { 173 | assert (!old_size); 174 | } 175 | return p; 176 | } 177 | 178 | void *tgl_realloc_release (void *ptr, size_t old_size __attribute__ ((unused)), size_t size) { 179 | total_allocated_bytes += (size - old_size); 180 | void *p = realloc (ptr, size); 181 | ensure_ptr (p); 182 | return p; 183 | } 184 | 185 | void *tgl_alloc_debug (size_t size) { 186 | total_allocated_bytes += size; 187 | void *p = malloc (size + RES_PRE + RES_AFTER); 188 | ensure_ptr (p); 189 | *(int *)p = size ^ 0xbedabeda; 190 | *(int *)(p + 4) = size; 191 | *(int *)(p + RES_PRE + size) = size ^ 0x7bed7bed; 192 | *(int *)(p + RES_AFTER + 4 + size) = used_blocks; 193 | blocks[used_blocks ++] = p; 194 | 195 | //tcheck (); 196 | return p + 8; 197 | } 198 | 199 | void *tgl_alloc_release (size_t size) { 200 | total_allocated_bytes += size; 201 | void *p = malloc (size); 202 | ensure_ptr (p); 203 | return p; 204 | } 205 | 206 | void *tgl_alloc0 (size_t size) { 207 | void *p = talloc (size); 208 | memset (p, 0, size); 209 | return p; 210 | } 211 | 212 | char *tgl_strdup (const char *s) { 213 | int l = strlen (s); 214 | char *p = talloc (l + 1); 215 | memcpy (p, s, l + 1); 216 | return p; 217 | } 218 | 219 | char *tgl_strndup (const char *s, size_t n) { 220 | size_t l = 0; 221 | for (l = 0; l < n && s[l]; l++) { } 222 | char *p = talloc (l + 1); 223 | memcpy (p, s, l); 224 | p[l] = 0; 225 | return p; 226 | } 227 | 228 | void *tgl_memdup (const void *s, size_t n) { 229 | void *r = talloc (n); 230 | memcpy (r, s, n); 231 | return r; 232 | } 233 | 234 | 235 | int tgl_inflate (void *input, int ilen, void *output, int olen) { 236 | z_stream strm; 237 | memset (&strm, 0, sizeof (strm)); 238 | assert (inflateInit2 (&strm, 16 + MAX_WBITS) == Z_OK); 239 | strm.avail_in = ilen; 240 | strm.next_in = input; 241 | strm.avail_out = olen ; 242 | strm.next_out = output; 243 | int err = inflate (&strm, Z_FINISH); 244 | int total_out = strm.total_out; 245 | 246 | if (err != Z_OK && err != Z_STREAM_END) { 247 | logprintf ( "inflate error = %d\n", err); 248 | logprintf ( "inflated %d bytes\n", (int) strm.total_out); 249 | total_out = 0; 250 | } 251 | inflateEnd (&strm); 252 | return total_out; 253 | } 254 | 255 | void tgl_check_debug (void) { 256 | int i; 257 | for (i = 0; i < used_blocks; i++) { 258 | void *ptr = blocks[i]; 259 | int size = (*(int *)ptr) ^ 0xbedabeda; 260 | if (!(*(int *)(ptr + 4) == size) || 261 | !(*(int *)(ptr + RES_PRE + size) == (size ^ 0x7bed7bed)) || 262 | !(*(int *)(ptr + RES_PRE + 4 + size) == i)) { 263 | logprintf ("Bad block at address %p (size %d, num %d)\n", ptr, size, i); 264 | assert (0 && "Bad block"); 265 | } 266 | } 267 | for (i = 0; i < free_blocks_cnt; i++) { 268 | void *ptr = free_blocks[i]; 269 | int l = *(int *)ptr; 270 | int j = 0; 271 | for (j = 0; j < l; j++) { 272 | if (*(char *)(ptr + 4 + j)) { 273 | hexdump (ptr + 8, ptr + 8 + l + ((-l) & 3)); 274 | logprintf ("Used freed memory size = %d. ptr = %p\n", l + 4 - RES_PRE - RES_AFTER, ptr); 275 | assert (0); 276 | } 277 | } 278 | } 279 | //logprintf ("ok. Used_blocks = %d. Free blocks = %d\n", used_blocks, free_blocks_cnt); 280 | } 281 | 282 | void tgl_exists_debug (void *ptr, int size) { 283 | ptr -= RES_PRE; 284 | if (size != (int)((*(int *)ptr) ^ 0xbedabeda)) { 285 | logprintf ("size = %d, ptr = %d\n", size, (*(int *)ptr) ^ 0xbedabeda); 286 | } 287 | assert (*(int *)ptr == (int)((size) ^ 0xbedabeda)); 288 | assert (*(int *)(ptr + RES_PRE + size) == (int)((size) ^ 0x7bed7bed)); 289 | assert (*(int *)(ptr + 4) == size); 290 | int block_num = *(int *)(ptr + 4 + RES_PRE + size); 291 | if (block_num >= used_blocks) { 292 | logprintf ("block_num = %d, used = %d\n", block_num, used_blocks); 293 | } 294 | assert (block_num < used_blocks); 295 | } 296 | 297 | void tgl_exists_release (void *ptr, int size) {} 298 | void tgl_check_release (void) {} 299 | 300 | void tgl_my_clock_gettime (int clock_id, struct timespec *T) { 301 | #ifdef __MACH__ 302 | // We are ignoring MONOTONIC and hope time doesn't go back too often 303 | clock_serv_t cclock; 304 | mach_timespec_t mts; 305 | host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &cclock); 306 | clock_get_time(cclock, &mts); 307 | mach_port_deallocate(mach_task_self(), cclock); 308 | T->tv_sec = mts.tv_sec; 309 | T->tv_nsec = mts.tv_nsec; 310 | #else 311 | assert (clock_gettime(clock_id, T) >= 0); 312 | #endif 313 | } 314 | 315 | double tglt_get_double_time (void) { 316 | struct timespec tv; 317 | tgl_my_clock_gettime (CLOCK_REALTIME, &tv); 318 | return tv.tv_sec + 1e-9 * tv.tv_nsec; 319 | } 320 | 321 | void tglt_secure_random (void *s, int l) { 322 | if (TGLC_rand_bytes (s, l) <= 0) { 323 | /*if (allow_weak_random) { 324 | TGLC_rand_pseudo_bytes (s, l); 325 | } else {*/ 326 | assert (0 && "End of random. If you want, you can start with -w"); 327 | //} 328 | } else { 329 | #ifdef VALGRIND_FIXES 330 | VALGRIND_MAKE_MEM_DEFINED (s, l); 331 | VALGRIND_CHECK_MEM_IS_DEFINED (s, l); 332 | #endif 333 | } 334 | } 335 | 336 | struct tgl_allocator tgl_allocator_debug = { 337 | .alloc = tgl_alloc_debug, 338 | .realloc = tgl_realloc_debug, 339 | .free = tgl_free_debug, 340 | .check = tgl_check_debug, 341 | .exists = tgl_exists_debug 342 | }; 343 | 344 | struct tgl_allocator tgl_allocator_release = { 345 | .alloc = tgl_alloc_release, 346 | .realloc = tgl_realloc_release, 347 | .free = tgl_free_release, 348 | .check = tgl_check_release, 349 | .exists = tgl_exists_release 350 | }; 351 | 352 | long long tgl_get_allocated_bytes (void) { 353 | return total_allocated_bytes; 354 | } 355 | struct tgl_allocator *tgl_allocator = &tgl_allocator_release; 356 | -------------------------------------------------------------------------------- /tools.h: -------------------------------------------------------------------------------- 1 | /* 2 | This file is part of tgl-library 3 | 4 | This library is free software; you can redistribute it and/or 5 | modify it under the terms of the GNU Lesser General Public 6 | License as published by the Free Software Foundation; either 7 | version 2.1 of the License, or (at your option) any later version. 8 | 9 | This library is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 | Lesser General Public License for more details. 13 | 14 | You should have received a copy of the GNU Lesser General Public 15 | License along with this library; if not, write to the Free Software 16 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 17 | 18 | Copyright Vitaly Valtman 2013-2015 19 | */ 20 | 21 | #ifndef __TOOLS_H__ 22 | #define __TOOLS_H__ 23 | #include 24 | #include 25 | #include 26 | #include 27 | #include 28 | //#include "tgl.h" 29 | #include "crypto/err.h" 30 | #include "crypto/rand.h" 31 | 32 | struct tgl_allocator { 33 | void *(*alloc)(size_t size); 34 | void *(*realloc)(void *ptr, size_t old_size, size_t size); 35 | void (*free)(void *ptr, int size); 36 | void (*check)(void); 37 | void (*exists)(void *ptr, int size); 38 | }; 39 | 40 | #define talloc tgl_allocator->alloc 41 | #define talloc0 tgl_alloc0 42 | #define tfree tgl_allocator->free 43 | #define tfree_str tgl_free_str 44 | #define tfree_secure tgl_free_secure 45 | #define trealloc tgl_allocator->realloc 46 | #define tcheck tgl_allocator->check 47 | #define texists tgl_allocator->exists 48 | #define tstrdup tgl_strdup 49 | #define tmemdup tgl_memdup 50 | #define tstrndup tgl_strndup 51 | #define tasprintf tgl_asprintf 52 | #define tsnprintf tgl_snprintf 53 | 54 | 55 | extern struct tgl_allocator *tgl_allocator; 56 | double tglt_get_double_time (void); 57 | 58 | int tgl_inflate (void *input, int ilen, void *output, int olen); 59 | //void ensure (int r); 60 | //void ensure_ptr (void *p); 61 | 62 | static inline void out_of_memory (void) { 63 | fprintf (stderr, "Out of memory\n"); 64 | exit (1); 65 | } 66 | 67 | static inline void ensure (int r) { 68 | if (!r) { 69 | fprintf (stderr, "Crypto error\n"); 70 | TGLC_err_print_errors_fp (stderr); 71 | assert (0); 72 | } 73 | } 74 | 75 | static inline void ensure_ptr (void *p) { 76 | if (p == NULL) { 77 | out_of_memory (); 78 | } 79 | } 80 | 81 | void *tgl_alloc_debug (size_t size); 82 | void *tgl_alloc_release (size_t size); 83 | 84 | void *tgl_realloc_debug (void *ptr, size_t old_size, size_t size); 85 | void *tgl_realloc_release (void *ptr, size_t old_size, size_t size); 86 | 87 | void *tgl_alloc0 (size_t size); 88 | char *tgl_strdup (const char *s); 89 | char *tgl_strndup (const char *s, size_t n); 90 | 91 | void tgl_free_debug (void *ptr, int size); 92 | void tgl_free_release (void *ptr, int size); 93 | //void tgl_free_str (void *ptr); 94 | //void tgl_free_secure (void *ptr, int size); 95 | 96 | void tgl_check_debug (void); 97 | void tgl_exists_debug (void *ptr, int size); 98 | void tgl_check_release (void); 99 | void tgl_exists_release (void *ptr, int size); 100 | 101 | void *tgl_memdup (const void *s, size_t n); 102 | 103 | int tgl_snprintf (char *buf, int len, const char *format, ...) __attribute__ ((format (__printf__, 3, 4))); 104 | int tgl_asprintf (char **res, const char *format, ...) __attribute__ ((format (__printf__, 2, 3))); 105 | 106 | void tglt_secure_random (void *s, int l); 107 | void tgl_my_clock_gettime (int clock_id, struct timespec *T); 108 | 109 | static inline void tgl_free_str (void *ptr) { 110 | if (!ptr) { return; } 111 | tfree (ptr, strlen ((const char *)ptr) + 1); 112 | } 113 | 114 | static inline void tgl_free_secure (void *ptr, int size) { 115 | memset (ptr, 0, size); 116 | tfree (ptr, size); 117 | } 118 | 119 | static inline void hexdump (void *ptr, void *end_ptr) { 120 | int total = 0; 121 | unsigned char *bptr = (unsigned char *)ptr; 122 | while (bptr < (unsigned char *)end_ptr) { 123 | fprintf (stderr, "%02x", (int)*bptr); 124 | bptr ++; 125 | total ++; 126 | if (total == 16) { 127 | fprintf (stderr, "\n"); 128 | total = 0; 129 | } 130 | } 131 | if (total) { fprintf (stderr, "\n"); } 132 | } 133 | 134 | #endif 135 | -------------------------------------------------------------------------------- /tree.h: -------------------------------------------------------------------------------- 1 | /* 2 | This file is part of tgl-library 3 | 4 | This library is free software; you can redistribute it and/or 5 | modify it under the terms of the GNU Lesser General Public 6 | License as published by the Free Software Foundation; either 7 | version 2.1 of the License, or (at your option) any later version. 8 | 9 | This library is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 | Lesser General Public License for more details. 13 | 14 | You should have received a copy of the GNU Lesser General Public 15 | License along with this library; if not, write to the Free Software 16 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 17 | 18 | Copyright Vitaly Valtman 2013-2015 19 | */ 20 | #ifndef __TREE_H__ 21 | #define __TREE_H__ 22 | #include 23 | 24 | #include 25 | #include 26 | #include "tools.h" 27 | 28 | #pragma pack(push,4) 29 | #define DEFINE_TREE(X_NAME, X_TYPE, X_CMP, X_UNSET) \ 30 | struct tree_ ## X_NAME { \ 31 | struct tree_ ## X_NAME *left, *right;\ 32 | X_TYPE x;\ 33 | int y;\ 34 | };\ 35 | \ 36 | static struct tree_ ## X_NAME *new_tree_node_ ## X_NAME (X_TYPE x, int y) {\ 37 | struct tree_ ## X_NAME *T = talloc (sizeof (*T));\ 38 | T->x = x;\ 39 | T->y = y;\ 40 | T->left = T->right = 0;\ 41 | return T;\ 42 | }\ 43 | \ 44 | static void delete_tree_node_ ## X_NAME (struct tree_ ## X_NAME *T) {\ 45 | tfree (T, sizeof (*T));\ 46 | }\ 47 | \ 48 | static void tree_split_ ## X_NAME (struct tree_ ## X_NAME *T, X_TYPE x, struct tree_ ## X_NAME **L, struct tree_ ## X_NAME **R) {\ 49 | if (!T) {\ 50 | *L = *R = 0;\ 51 | } else {\ 52 | int c = X_CMP (x, T->x);\ 53 | if (c < 0) {\ 54 | tree_split_ ## X_NAME (T->left, x, L, &T->left);\ 55 | *R = T;\ 56 | } else {\ 57 | tree_split_ ## X_NAME (T->right, x, &T->right, R);\ 58 | *L = T;\ 59 | }\ 60 | }\ 61 | }\ 62 | \ 63 | static struct tree_ ## X_NAME *tree_insert_ ## X_NAME (struct tree_ ## X_NAME *T, X_TYPE x, int y) __attribute__ ((warn_unused_result,unused));\ 64 | static struct tree_ ## X_NAME *tree_insert_ ## X_NAME (struct tree_ ## X_NAME *T, X_TYPE x, int y) {\ 65 | if (!T) {\ 66 | return new_tree_node_ ## X_NAME (x, y);\ 67 | } else {\ 68 | if (y > T->y) {\ 69 | struct tree_ ## X_NAME *N = new_tree_node_ ## X_NAME (x, y);\ 70 | tree_split_ ## X_NAME (T, x, &N->left, &N->right);\ 71 | return N;\ 72 | } else {\ 73 | int c = X_CMP (x, T->x);\ 74 | assert (c);\ 75 | if (c < 0) { \ 76 | T->left = tree_insert_ ## X_NAME (T->left, x, y);\ 77 | } else { \ 78 | T->right = tree_insert_ ## X_NAME (T->right, x, y);\ 79 | } \ 80 | return T; \ 81 | }\ 82 | }\ 83 | }\ 84 | \ 85 | static struct tree_ ## X_NAME *tree_merge_ ## X_NAME (struct tree_ ## X_NAME *L, struct tree_ ## X_NAME *R) {\ 86 | if (!L || !R) {\ 87 | return L ? L : R;\ 88 | } else {\ 89 | if (L->y > R->y) {\ 90 | L->right = tree_merge_ ## X_NAME (L->right, R);\ 91 | return L;\ 92 | } else {\ 93 | R->left = tree_merge_ ## X_NAME (L, R->left);\ 94 | return R;\ 95 | }\ 96 | }\ 97 | }\ 98 | \ 99 | static struct tree_ ## X_NAME *tree_delete_ ## X_NAME (struct tree_ ## X_NAME *T, X_TYPE x) __attribute__ ((warn_unused_result,unused));\ 100 | static struct tree_ ## X_NAME *tree_delete_ ## X_NAME (struct tree_ ## X_NAME *T, X_TYPE x) {\ 101 | assert (T);\ 102 | int c = X_CMP (x, T->x);\ 103 | if (!c) {\ 104 | struct tree_ ## X_NAME *N = tree_merge_ ## X_NAME (T->left, T->right);\ 105 | delete_tree_node_ ## X_NAME (T);\ 106 | return N;\ 107 | } else {\ 108 | if (c < 0) { \ 109 | T->left = tree_delete_ ## X_NAME (T->left, x); \ 110 | } else { \ 111 | T->right = tree_delete_ ## X_NAME (T->right, x); \ 112 | } \ 113 | return T; \ 114 | }\ 115 | }\ 116 | \ 117 | static X_TYPE tree_get_min_ ## X_NAME (struct tree_ ## X_NAME *t) __attribute__ ((unused));\ 118 | static X_TYPE tree_get_min_ ## X_NAME (struct tree_ ## X_NAME *T) {\ 119 | if (!T) { return X_UNSET; } \ 120 | while (T->left) { T = T->left; }\ 121 | return T->x; \ 122 | } \ 123 | \ 124 | static X_TYPE tree_lookup_ ## X_NAME (struct tree_ ## X_NAME *T, X_TYPE x) __attribute__ ((unused));\ 125 | static X_TYPE tree_lookup_ ## X_NAME (struct tree_ ## X_NAME *T, X_TYPE x) {\ 126 | int c;\ 127 | while (T && (c = X_CMP (x, T->x))) {\ 128 | T = (c < 0 ? T->left : T->right);\ 129 | }\ 130 | return T ? T->x : X_UNSET;\ 131 | }\ 132 | \ 133 | static void tree_act_ ## X_NAME (struct tree_ ## X_NAME *T, void (*act)(X_TYPE)) __attribute__ ((unused));\ 134 | static void tree_act_ ## X_NAME (struct tree_ ## X_NAME *T, void (*act)(X_TYPE)) {\ 135 | if (!T) { return; } \ 136 | tree_act_ ## X_NAME (T->left, act); \ 137 | act (T->x); \ 138 | tree_act_ ## X_NAME (T->right, act); \ 139 | }\ 140 | \ 141 | static void tree_act_ex_ ## X_NAME (struct tree_ ## X_NAME *T, void (*act)(X_TYPE, void *), void *extra) __attribute__ ((unused));\ 142 | static void tree_act_ex_ ## X_NAME (struct tree_ ## X_NAME *T, void (*act)(X_TYPE, void *), void *extra) {\ 143 | if (!T) { return; } \ 144 | tree_act_ex_ ## X_NAME (T->left, act, extra); \ 145 | act (T->x, extra); \ 146 | tree_act_ex_ ## X_NAME (T->right, act, extra); \ 147 | }\ 148 | \ 149 | static int tree_count_ ## X_NAME (struct tree_ ## X_NAME *T) __attribute__ ((unused));\ 150 | static int tree_count_ ## X_NAME (struct tree_ ## X_NAME *T) { \ 151 | if (!T) { return 0; }\ 152 | return 1 + tree_count_ ## X_NAME (T->left) + tree_count_ ## X_NAME (T->right); \ 153 | }\ 154 | static void tree_check_ ## X_NAME (struct tree_ ## X_NAME *T) __attribute__ ((unused));\ 155 | static void tree_check_ ## X_NAME (struct tree_ ## X_NAME *T) { \ 156 | if (!T) { return; }\ 157 | if (T->left) { \ 158 | assert (T->left->y <= T->y);\ 159 | assert (X_CMP (T->left->x, T->x) < 0); \ 160 | }\ 161 | if (T->right) { \ 162 | assert (T->right->y <= T->y);\ 163 | assert (X_CMP (T->right->x, T->x) > 0); \ 164 | }\ 165 | tree_check_ ## X_NAME (T->left); \ 166 | tree_check_ ## X_NAME (T->right); \ 167 | }\ 168 | static struct tree_ ## X_NAME *tree_clear_ ## X_NAME (struct tree_ ## X_NAME *T) __attribute__ ((unused));\ 169 | static struct tree_ ## X_NAME *tree_clear_ ## X_NAME (struct tree_ ## X_NAME *T) { \ 170 | if (!T) { return 0; }\ 171 | tree_clear_ ## X_NAME (T->left); \ 172 | tree_clear_ ## X_NAME (T->right); \ 173 | delete_tree_node_ ## X_NAME (T); \ 174 | return 0; \ 175 | } \ 176 | 177 | #define int_cmp(a,b) ((a) - (b)) 178 | #pragma pack(pop) 179 | #endif 180 | -------------------------------------------------------------------------------- /updates.h: -------------------------------------------------------------------------------- 1 | /* 2 | This file is part of tgl-library 3 | 4 | This library is free software; you can redistribute it and/or 5 | modify it under the terms of the GNU Lesser General Public 6 | License as published by the Free Software Foundation; either 7 | version 2.1 of the License, or (at your option) any later version. 8 | 9 | This library is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 | Lesser General Public License for more details. 13 | 14 | You should have received a copy of the GNU Lesser General Public 15 | License along with this library; if not, write to the Free Software 16 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 17 | 18 | Copyright Vitaly Valtman 2013-2015 19 | */ 20 | 21 | #ifndef __UPDATES_H__ 22 | #define __UPDATES_H__ 23 | struct tl_ds_updates; 24 | struct tl_ds_update; 25 | void tgl_insert_status_update (struct tgl_state *TLS, struct tgl_user *U); 26 | void tgl_insert_status_expire (struct tgl_state *TLS, struct tgl_user *U); 27 | void tgl_remove_status_expire (struct tgl_state *TLS, struct tgl_user *U); 28 | 29 | int tgl_check_pts_diff (struct tgl_state *TLS, int pts, int pts_count); 30 | void tglu_work_update (struct tgl_state *TLS, int check_only, struct tl_ds_update *DS_U); 31 | void tglu_work_updates (struct tgl_state *TLS, int check_only, struct tl_ds_updates *DS_U); 32 | void tglu_work_any_updates_buf (struct tgl_state *TLS); 33 | void tglu_work_any_updates (struct tgl_state *TLS, int check_only, struct tl_ds_updates *DS_U, void *extra); 34 | #endif 35 | --------------------------------------------------------------------------------