Changed vserver.h to look up the slice id corresponding to an xid from
[fprobe-ulog.git] / src / vserver.h
1 #ifndef __VSERVER_H__
2 #define __VSERVER_H__
3
4 #include <pwd.h>
5 #include <stdint.h>
6 #include <stdlib.h>
7 #include <stdio.h>
8 #include <string.h>
9
10 #define VSERVER_CONFIG_PATH "/etc/vservers"
11 #define SLICE_ID_FILE       "slice_id"
12
13 char* get_current_username (unsigned int uid)
14 {
15     struct passwd *passwd_entry;
16     if ((passwd_entry = getpwuid(uid)) == NULL) {
17         fprintf(stderr, "Could not look up user record for %d\n", uid);
18         return NULL; 
19     }
20
21     return (strdup(passwd_entry->pw_name));
22 }
23
24 #define HASH_SIZE           (1<<12)
25 #define HASH_TABLE_MASK     (HASH_SIZE - 1)
26
27 struct hash_entry {
28     unsigned int xid;
29     uint32_t slice_id;
30 };
31
32 struct hash_entry slice_id_hash[HASH_SIZE];
33
34 void set_hash_entry(unsigned int xid, uint32_t slice_id) {
35     int idx = xid & HASH_TABLE_MASK;
36     int i;
37     for (i = idx;i!=idx;i=(i+1) & HASH_TABLE_MASK) {
38         struct hash_entry *entry = &slice_id_hash[i];
39         if (entry->xid == 0 || entry->xid == xid) {
40             entry->xid = slice_id;
41             break;
42         }
43     }
44 }
45
46 uint32_t xid_to_slice_id_slow(unsigned int xid) {
47     uint32_t slice_id;
48     char *slice_name = get_current_username (xid);
49     char *slice_path = (char *) malloc(sizeof(VSERVER_CONFIG_PATH) + strlen(slice_name) + sizeof(SLICE_ID_FILE) + sizeof("//"));
50     sprintf(slice_path,"%s/%s/%s",VSERVER_CONFIG_PATH,slice_name,SLICE_ID_FILE);
51     FILE *fp = fopen(slice_path, "r");
52     if (fp) {
53         fscanf(fp,"%u",&slice_id);
54         set_hash_entry(xid, slice_id);
55     }
56     fclose(fp);
57     return slice_id;
58 }
59
60 uint32_t xid_to_slice_id_fast(unsigned int xid) {
61     int idx = xid & HASH_TABLE_MASK;
62     int i;
63     uint32_t slice_id;
64     for (i = idx;i!=idx;i=(i+1) & HASH_TABLE_MASK) {
65         struct hash_entry *entry = &slice_id_hash[i];
66         if (entry->xid == xid) {
67             entry->xid = slice_id;
68             break;
69         }
70     }
71     
72 }
73
74 uint32_t xid_to_slice_id(unsigned int xid) {
75     uint32_t slice_id;
76     if (xid == 0)
77         return 0;
78     else if ((slice_id = xid_to_slice_id_fast(xid)) != 0)
79         return slice_id;
80     else
81         return xid_to_slice_id_slow(xid);
82 }
83
84 #endif