1/*
2 This file is part of Mtproto-proxy Library.
3
4 Mtproto-proxy Library is free software: you can redistribute it and/or modify
5 it under the terms of the GNU Lesser 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 Mtproto-proxy 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
12 GNU Lesser General Public License for more details.
13
14 You should have received a copy of the GNU Lesser General Public License
15 along with Mtproto-proxy Library. If not, see <http://www.gnu.org/licenses/>.
16
17 Copyright 2011-2013 Vkontakte Ltd
18 2011-2013 Nikolai Durov
19 2011-2013 Andrey Lopatin
20
21 Copyright 2014 Telegram Messenger Inc
22 2014 Vitaly Valtman
23*/
24
25#define _FILE_OFFSET_BITS 64
26
27#include <assert.h>
28#include <string.h>
29#include <stdio.h>
30#include <stdlib.h>
31#include <unistd.h>
32#include <time.h>
33#include <sys/types.h>
34
35#include "common/pid.h"
36
37npid_t PID;
38
39void init_common_PID (void) {
40 if (!PID.pid) {
41 int p = getpid ();
42 assert (!(p & 0xffff0000));
43 PID.pid = p;
44 }
45 if (!PID.utime) {
46 PID.utime = time (0);
47 }
48}
49
50void init_client_PID (unsigned ip) {
51 if (ip && ip != 0x7f000001) {
52 PID.ip = ip;
53 }
54 // PID.port = 0;
55 init_common_PID ();
56};
57
58void init_server_PID (unsigned ip, int port) {
59 if (ip && ip != 0x7f000001) {
60 PID.ip = ip;
61 }
62 if (!PID.port) {
63 PID.port = port;
64 }
65 init_common_PID ();
66};
67
68/* returns 1 if X is a special case of Y, 2 if they match completely */
69int matches_pid (npid_t *X, npid_t *Y) {
70 if (!memcmp (X, Y, sizeof (struct process_id))) {
71 return 2;
72 } else if ((!Y->ip || X->ip == Y->ip) && (!Y->port || X->port == Y->port) && (!Y->pid || X->pid == Y->pid) && (!Y->utime || X->utime == Y->utime)) {
73 return 1;
74 } else {
75 return 0;
76 }
77}
78
79int process_id_is_newer (struct process_id *a, struct process_id *b) {
80 assert (!memcmp (a, b, 6));
81 if (a->utime < b->utime) { return 0; }
82 if (a->utime > b->utime) { return 1; }
83 int x = (a->pid - b->pid) & 0x7fff;
84 if (x && x <= 0x3fff) { return 1; }
85 return 0;
86}
87
88