s3:lib: split things into a conn_tdb.h
[samba.git] / source3 / utils / status.c
1 /* 
2    Unix SMB/CIFS implementation.
3    status reporting
4    Copyright (C) Andrew Tridgell 1994-1998
5
6    This program is free software; you can redistribute it and/or modify
7    it under the terms of the GNU General Public License as published by
8    the Free Software Foundation; either version 3 of the License, or
9    (at your option) any later version.
10
11    This program is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
15
16    You should have received a copy of the GNU General Public License
17    along with this program.  If not, see <http://www.gnu.org/licenses/>.
18
19    Revision History:
20
21    12 aug 96: Erik.Devriendt@te6.siemens.be
22    added support for shared memory implementation of share mode locking
23
24    21-Jul-1998: rsharpe@ns.aus.com (Richard Sharpe)
25    Added -L (locks only) -S (shares only) flags and code
26
27 */
28
29 /*
30  * This program reports current SMB connections
31  */
32
33 #include "includes.h"
34 #include "system/filesys.h"
35 #include "popt_common.h"
36 #include "dbwrap/dbwrap.h"
37 #include "dbwrap/dbwrap_open.h"
38 #include "../libcli/security/security.h"
39 #include "session.h"
40 #include "locking/proto.h"
41 #include "messages.h"
42 #include "librpc/gen_ndr/open_files.h"
43 #include "smbd/proto.h"
44 #include "librpc/gen_ndr/notify.h"
45 #include "lib/conn_tdb.h"
46
47 #define SMB_MAXPIDS             2048
48 static uid_t            Ucrit_uid = 0;               /* added by OH */
49 static struct server_id Ucrit_pid[SMB_MAXPIDS];  /* Ugly !!! */   /* added by OH */
50 static int              Ucrit_MaxPid=0;                    /* added by OH */
51 static unsigned int     Ucrit_IsActive = 0;                /* added by OH */
52
53 static bool verbose, brief;
54 static bool shares_only;            /* Added by RJS */
55 static bool locks_only;            /* Added by RJS */
56 static bool processes_only;
57 static bool show_brl;
58 static bool numeric_only;
59
60 const char *username = NULL;
61
62 extern bool status_profile_dump(bool be_verbose);
63 extern bool status_profile_rates(bool be_verbose);
64
65 /* added by OH */
66 static void Ucrit_addUid(uid_t uid)
67 {
68         Ucrit_uid = uid;
69         Ucrit_IsActive = 1;
70 }
71
72 static unsigned int Ucrit_checkUid(uid_t uid)
73 {
74         if ( !Ucrit_IsActive ) 
75                 return 1;
76
77         if ( uid == Ucrit_uid ) 
78                 return 1;
79
80         return 0;
81 }
82
83 static unsigned int Ucrit_checkPid(struct server_id pid)
84 {
85         int i;
86
87         if ( !Ucrit_IsActive ) 
88                 return 1;
89
90         for (i=0;i<Ucrit_MaxPid;i++) {
91                 if (cluster_id_equal(&pid, &Ucrit_pid[i])) 
92                         return 1;
93         }
94
95         return 0;
96 }
97
98 static bool Ucrit_addPid( struct server_id pid )
99 {
100         if ( !Ucrit_IsActive )
101                 return True;
102
103         if ( Ucrit_MaxPid >= SMB_MAXPIDS ) {
104                 d_printf("ERROR: More than %d pids for user %s!\n",
105                          SMB_MAXPIDS, uidtoname(Ucrit_uid));
106
107                 return False;
108         }
109
110         Ucrit_pid[Ucrit_MaxPid++] = pid;
111
112         return True;
113 }
114
115 static void print_share_mode(const struct share_mode_entry *e,
116                              const char *sharepath,
117                              const char *fname,
118                              void *dummy)
119 {
120         static int count;
121
122         if (!is_valid_share_mode_entry(e)) {
123                 return;
124         }
125
126         if (!process_exists(e->pid)) {
127                 return;
128         }
129
130         if (count==0) {
131                 d_printf("Locked files:\n");
132                 d_printf("Pid          Uid        DenyMode   Access      R/W        Oplock           SharePath   Name   Time\n");
133                 d_printf("--------------------------------------------------------------------------------------------------\n");
134         }
135         count++;
136
137         if (Ucrit_checkPid(e->pid)) {
138                 d_printf("%-11s  ",procid_str_static(&e->pid));
139                 d_printf("%-9u  ", (unsigned int)e->uid);
140                 switch (map_share_mode_to_deny_mode(e->share_access,
141                                                     e->private_options)) {
142                         case DENY_NONE: d_printf("DENY_NONE  "); break;
143                         case DENY_ALL:  d_printf("DENY_ALL   "); break;
144                         case DENY_DOS:  d_printf("DENY_DOS   "); break;
145                         case DENY_READ: d_printf("DENY_READ  "); break;
146                         case DENY_WRITE:printf("DENY_WRITE "); break;
147                         case DENY_FCB:  d_printf("DENY_FCB "); break;
148                         default: {
149                                 d_printf("unknown-please report ! "
150                                          "e->share_access = 0x%x, "
151                                          "e->private_options = 0x%x\n",
152                                          (unsigned int)e->share_access,
153                                          (unsigned int)e->private_options );
154                                 break;
155                         }
156                 }
157                 d_printf("0x%-8x  ",(unsigned int)e->access_mask);
158                 if ((e->access_mask & (FILE_READ_DATA|FILE_WRITE_DATA))==
159                                 (FILE_READ_DATA|FILE_WRITE_DATA)) {
160                         d_printf("RDWR       ");
161                 } else if (e->access_mask & FILE_WRITE_DATA) {
162                         d_printf("WRONLY     ");
163                 } else {
164                         d_printf("RDONLY     ");
165                 }
166
167                 if((e->op_type & (EXCLUSIVE_OPLOCK|BATCH_OPLOCK)) == 
168                                         (EXCLUSIVE_OPLOCK|BATCH_OPLOCK)) {
169                         d_printf("EXCLUSIVE+BATCH ");
170                 } else if (e->op_type & EXCLUSIVE_OPLOCK) {
171                         d_printf("EXCLUSIVE       ");
172                 } else if (e->op_type & BATCH_OPLOCK) {
173                         d_printf("BATCH           ");
174                 } else if (e->op_type & LEVEL_II_OPLOCK) {
175                         d_printf("LEVEL_II        ");
176                 } else {
177                         d_printf("NONE            ");
178                 }
179
180                 d_printf(" %s   %s   %s",sharepath, fname, time_to_asc((time_t)e->time.tv_sec));
181         }
182 }
183
184 static void print_brl(struct file_id id,
185                         struct server_id pid, 
186                         enum brl_type lock_type,
187                         enum brl_flavour lock_flav,
188                         br_off start,
189                         br_off size,
190                         void *private_data)
191 {
192         static int count;
193         int i;
194         static const struct {
195                 enum brl_type lock_type;
196                 const char *desc;
197         } lock_types[] = {
198                 { READ_LOCK, "R" },
199                 { WRITE_LOCK, "W" },
200                 { PENDING_READ_LOCK, "PR" },
201                 { PENDING_WRITE_LOCK, "PW" },
202                 { UNLOCK_LOCK, "U" }
203         };
204         const char *desc="X";
205         const char *sharepath = "";
206         char *fname = NULL;
207         struct share_mode_lock *share_mode;
208
209         if (count==0) {
210                 d_printf("Byte range locks:\n");
211                 d_printf("Pid        dev:inode       R/W  start     size      SharePath               Name\n");
212                 d_printf("--------------------------------------------------------------------------------\n");
213         }
214         count++;
215
216         share_mode = fetch_share_mode_unlocked(NULL, id);
217         if (share_mode) {
218                 bool has_stream = share_mode->data->stream_name != NULL;
219
220                 fname = talloc_asprintf(NULL, "%s%s%s",
221                                         share_mode->data->base_name,
222                                         has_stream ? ":" : "",
223                                         has_stream ?
224                                         share_mode->data->stream_name :
225                                         "");
226         } else {
227                 fname = talloc_strdup(NULL, "");
228                 if (fname == NULL) {
229                         return;
230                 }
231         }
232
233         for (i=0;i<ARRAY_SIZE(lock_types);i++) {
234                 if (lock_type == lock_types[i].lock_type) {
235                         desc = lock_types[i].desc;
236                 }
237         }
238
239         d_printf("%-10s %-15s %-4s %-9.0f %-9.0f %-24s %-24s\n", 
240                  procid_str_static(&pid), file_id_string_tos(&id),
241                  desc,
242                  (double)start, (double)size,
243                  sharepath, fname);
244
245         TALLOC_FREE(fname);
246         TALLOC_FREE(share_mode);
247 }
248
249 static int traverse_fn1(const struct connections_key *key,
250                         const struct connections_data *crec,
251                         void *state)
252 {
253         if (crec->cnum == -1)
254                 return 0;
255
256         if (!process_exists(crec->pid) || !Ucrit_checkUid(crec->uid)) {
257                 return 0;
258         }
259
260         d_printf("%-10s   %s   %-12s  %s",
261                  crec->servicename,procid_str_static(&crec->pid),
262                  crec->machine,
263                  time_to_asc(crec->start));
264
265         return 0;
266 }
267
268 static int traverse_sessionid(const char *key, struct sessionid *session,
269                               void *private_data)
270 {
271         fstring uid_str, gid_str;
272
273         if (!process_exists(session->pid)
274             || !Ucrit_checkUid(session->uid)) {
275                 return 0;
276         }
277
278         Ucrit_addPid(session->pid);
279
280         fstr_sprintf(uid_str, "%u", (unsigned int)session->uid);
281         fstr_sprintf(gid_str, "%u", (unsigned int)session->gid);
282
283         d_printf("%-7s   %-12s  %-12s  %-12s (%s)\n",
284                  procid_str_static(&session->pid),
285                  numeric_only ? uid_str : uidtoname(session->uid),
286                  numeric_only ? gid_str : gidtoname(session->gid),
287                  session->remote_machine, session->hostname);
288
289         return 0;
290 }
291
292
293 static void print_notify_recs(const char *path,
294                               struct notify_db_entry *entries,
295                               size_t num_entries,
296                               time_t deleted_time, void *private_data)
297 {
298         size_t i;
299         d_printf("%s\n", path);
300
301         if (num_entries == 0) {
302                 d_printf("deleted %s\n", time_to_asc(deleted_time));
303         }
304
305         for (i=0; i<num_entries; i++) {
306                 struct notify_db_entry *e = &entries[i];
307                 char *str;
308
309                 str = server_id_str(talloc_tos(), &e->server);
310                 printf("%s %x %x\n", str, (unsigned)e->filter,
311                        (unsigned)e->subdir_filter);
312                 TALLOC_FREE(str);
313         }
314         printf("\n");
315 }
316
317  int main(int argc, char *argv[])
318 {
319         int c;
320         int profile_only = 0;
321         bool show_processes, show_locks, show_shares;
322         bool show_notify = false;
323         poptContext pc;
324         struct poptOption long_options[] = {
325                 POPT_AUTOHELP
326                 {"processes",   'p', POPT_ARG_NONE,     NULL, 'p', "Show processes only" },
327                 {"verbose",     'v', POPT_ARG_NONE,     NULL, 'v', "Be verbose" },
328                 {"locks",       'L', POPT_ARG_NONE,     NULL, 'L', "Show locks only" },
329                 {"shares",      'S', POPT_ARG_NONE,     NULL, 'S', "Show shares only" },
330                 {"notify",      'N', POPT_ARG_NONE,     NULL, 'N', "Show notifies" },
331                 {"user",        'u', POPT_ARG_STRING,   &username, 'u', "Switch to user" },
332                 {"brief",       'b', POPT_ARG_NONE,     NULL, 'b', "Be brief" },
333                 {"profile",     'P', POPT_ARG_NONE, NULL, 'P', "Do profiling" },
334                 {"profile-rates", 'R', POPT_ARG_NONE, NULL, 'R', "Show call rates" },
335                 {"byterange",   'B', POPT_ARG_NONE,     NULL, 'B', "Include byte range locks"},
336                 {"numeric",     'n', POPT_ARG_NONE,     NULL, 'n', "Numeric uid/gid"},
337                 POPT_COMMON_SAMBA
338                 POPT_TABLEEND
339         };
340         TALLOC_CTX *frame = talloc_stackframe();
341         int ret = 0;
342         struct messaging_context *msg_ctx;
343
344         sec_init();
345         load_case_tables();
346
347         setup_logging(argv[0], DEBUG_STDERR);
348
349         if (getuid() != geteuid()) {
350                 d_printf("smbstatus should not be run setuid\n");
351                 ret = 1;
352                 goto done;
353         }
354
355         pc = poptGetContext(NULL, argc, (const char **) argv, long_options, 
356                             POPT_CONTEXT_KEEP_FIRST);
357
358         while ((c = poptGetNextOpt(pc)) != -1) {
359                 switch (c) {
360                 case 'p':
361                         processes_only = true;
362                         break;
363                 case 'v':
364                         verbose = true;
365                         break;
366                 case 'L':
367                         locks_only = true;
368                         break;
369                 case 'S':
370                         shares_only = true;
371                         break;
372                 case 'N':
373                         show_notify = true;
374                         break;
375                 case 'b':
376                         brief = true;
377                         break;
378                 case 'u':
379                         Ucrit_addUid(nametouid(poptGetOptArg(pc)));
380                         break;
381                 case 'P':
382                 case 'R':
383                         profile_only = c;
384                         break;
385                 case 'B':
386                         show_brl = true;
387                         break;
388                 case 'n':
389                         numeric_only = true;
390                         break;
391                 }
392         }
393
394         /* setup the flags based on the possible combincations */
395
396         show_processes = !(shares_only || locks_only || profile_only) || processes_only;
397         show_locks     = !(shares_only || processes_only || profile_only) || locks_only;
398         show_shares    = !(processes_only || locks_only || profile_only) || shares_only;
399
400         if ( username )
401                 Ucrit_addUid( nametouid(username) );
402
403         if (verbose) {
404                 d_printf("using configfile = %s\n", get_dyn_CONFIGFILE());
405         }
406
407         if (!lp_load_initial_only(get_dyn_CONFIGFILE())) {
408                 fprintf(stderr, "Can't load %s - run testparm to debug it\n",
409                         get_dyn_CONFIGFILE());
410                 ret = -1;
411                 goto done;
412         }
413
414
415         if (lp_clustering()) {
416                 /*
417                  * This implicitly initializes the global ctdbd
418                  * connection, usable by the db_open() calls further
419                  * down.
420                  */
421                 msg_ctx = messaging_init(NULL, event_context_init(NULL));
422                 if (msg_ctx == NULL) {
423                         fprintf(stderr, "messaging_init failed\n");
424                         ret = -1;
425                         goto done;
426                 }
427         }
428
429         if (!lp_load_global(get_dyn_CONFIGFILE())) {
430                 fprintf(stderr, "Can't load %s - run testparm to debug it\n",
431                         get_dyn_CONFIGFILE());
432                 ret = -1;
433                 goto done;
434         }
435
436         switch (profile_only) {
437                 case 'P':
438                         /* Dump profile data */
439                         return status_profile_dump(verbose);
440                 case 'R':
441                         /* Continuously display rate-converted data */
442                         return status_profile_rates(verbose);
443                 default:
444                         break;
445         }
446
447         if ( show_processes ) {
448                 d_printf("\nSamba version %s\n",samba_version_string());
449                 d_printf("PID     Username      Group         Machine                        \n");
450                 d_printf("-------------------------------------------------------------------\n");
451
452                 sessionid_traverse_read(traverse_sessionid, NULL);
453
454                 if (processes_only) {
455                         goto done;
456                 }
457         }
458
459         if ( show_shares ) {
460                 if (verbose) {
461                         d_printf("Opened %s\n", lock_path("connections.tdb"));
462                 }
463
464                 if (brief) {
465                         goto done;
466                 }
467
468                 d_printf("\nService      pid     machine       Connected at\n");
469                 d_printf("-------------------------------------------------------\n");
470
471                 connections_forall_read(traverse_fn1, NULL);
472
473                 d_printf("\n");
474
475                 if ( shares_only ) {
476                         goto done;
477                 }
478         }
479
480         if ( show_locks ) {
481                 int result;
482                 struct db_context *db;
483                 db = db_open(NULL, lock_path("locking.tdb"), 0,
484                              TDB_CLEAR_IF_FIRST|TDB_INCOMPATIBLE_HASH, O_RDONLY, 0,
485                              DBWRAP_LOCK_ORDER_1);
486
487                 if (!db) {
488                         d_printf("%s not initialised\n",
489                                  lock_path("locking.tdb"));
490                         d_printf("This is normal if an SMB client has never "
491                                  "connected to your server.\n");
492                         exit(0);
493                 } else {
494                         TALLOC_FREE(db);
495                 }
496
497                 if (!locking_init_readonly()) {
498                         d_printf("Can't initialise locking module - exiting\n");
499                         ret = 1;
500                         goto done;
501                 }
502
503                 result = share_mode_forall(print_share_mode, NULL);
504
505                 if (result == 0) {
506                         d_printf("No locked files\n");
507                 } else if (result < 0) {
508                         d_printf("locked file list truncated\n");
509                 }
510
511                 d_printf("\n");
512
513                 if (show_brl) {
514                         brl_forall(print_brl, NULL);
515                 }
516
517                 locking_end();
518         }
519
520         if (show_notify) {
521                 struct notify_context *n;
522
523                 n = notify_init(talloc_tos(), NULL, NULL);
524                 if (n == NULL) {
525                         goto done;
526                 }
527                 notify_walk(n, print_notify_recs, NULL);
528                 TALLOC_FREE(n);
529         }
530
531 done:
532         TALLOC_FREE(frame);
533         return ret;
534 }