s3-locking: move locking prototypes out of proto.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.h"
37 #include "../libcli/security/security.h"
38 #include "session.h"
39 #include "locking/proto.h"
40
41 #define SMB_MAXPIDS             2048
42 static uid_t            Ucrit_uid = 0;               /* added by OH */
43 static struct server_id Ucrit_pid[SMB_MAXPIDS];  /* Ugly !!! */   /* added by OH */
44 static int              Ucrit_MaxPid=0;                    /* added by OH */
45 static unsigned int     Ucrit_IsActive = 0;                /* added by OH */
46
47 static bool verbose, brief;
48 static bool shares_only;            /* Added by RJS */
49 static bool locks_only;            /* Added by RJS */
50 static bool processes_only;
51 static bool show_brl;
52 static bool numeric_only;
53
54 const char *username = NULL;
55
56 extern bool status_profile_dump(bool be_verbose);
57 extern bool status_profile_rates(bool be_verbose);
58
59 /* added by OH */
60 static void Ucrit_addUid(uid_t uid)
61 {
62         Ucrit_uid = uid;
63         Ucrit_IsActive = 1;
64 }
65
66 static unsigned int Ucrit_checkUid(uid_t uid)
67 {
68         if ( !Ucrit_IsActive ) 
69                 return 1;
70
71         if ( uid == Ucrit_uid ) 
72                 return 1;
73
74         return 0;
75 }
76
77 static unsigned int Ucrit_checkPid(struct server_id pid)
78 {
79         int i;
80
81         if ( !Ucrit_IsActive ) 
82                 return 1;
83
84         for (i=0;i<Ucrit_MaxPid;i++) {
85                 if (cluster_id_equal(&pid, &Ucrit_pid[i])) 
86                         return 1;
87         }
88
89         return 0;
90 }
91
92 static bool Ucrit_addPid( struct server_id pid )
93 {
94         if ( !Ucrit_IsActive )
95                 return True;
96
97         if ( Ucrit_MaxPid >= SMB_MAXPIDS ) {
98                 d_printf("ERROR: More than %d pids for user %s!\n",
99                          SMB_MAXPIDS, uidtoname(Ucrit_uid));
100
101                 return False;
102         }
103
104         Ucrit_pid[Ucrit_MaxPid++] = pid;
105
106         return True;
107 }
108
109 static void print_share_mode(const struct share_mode_entry *e,
110                              const char *sharepath,
111                              const char *fname,
112                              void *dummy)
113 {
114         static int count;
115
116         if (!is_valid_share_mode_entry(e)) {
117                 return;
118         }
119
120         if (!process_exists(e->pid)) {
121                 return;
122         }
123
124         if (count==0) {
125                 d_printf("Locked files:\n");
126                 d_printf("Pid          Uid        DenyMode   Access      R/W        Oplock           SharePath   Name   Time\n");
127                 d_printf("--------------------------------------------------------------------------------------------------\n");
128         }
129         count++;
130
131         if (Ucrit_checkPid(e->pid)) {
132                 d_printf("%-11s  ",procid_str_static(&e->pid));
133                 d_printf("%-9u  ", (unsigned int)e->uid);
134                 switch (map_share_mode_to_deny_mode(e->share_access,
135                                                     e->private_options)) {
136                         case DENY_NONE: d_printf("DENY_NONE  "); break;
137                         case DENY_ALL:  d_printf("DENY_ALL   "); break;
138                         case DENY_DOS:  d_printf("DENY_DOS   "); break;
139                         case DENY_READ: d_printf("DENY_READ  "); break;
140                         case DENY_WRITE:printf("DENY_WRITE "); break;
141                         case DENY_FCB:  d_printf("DENY_FCB "); break;
142                         default: {
143                                 d_printf("unknown-please report ! "
144                                          "e->share_access = 0x%x, "
145                                          "e->private_options = 0x%x\n",
146                                          (unsigned int)e->share_access,
147                                          (unsigned int)e->private_options );
148                                 break;
149                         }
150                 }
151                 d_printf("0x%-8x  ",(unsigned int)e->access_mask);
152                 if ((e->access_mask & (FILE_READ_DATA|FILE_WRITE_DATA))==
153                                 (FILE_READ_DATA|FILE_WRITE_DATA)) {
154                         d_printf("RDWR       ");
155                 } else if (e->access_mask & FILE_WRITE_DATA) {
156                         d_printf("WRONLY     ");
157                 } else {
158                         d_printf("RDONLY     ");
159                 }
160
161                 if((e->op_type & (EXCLUSIVE_OPLOCK|BATCH_OPLOCK)) == 
162                                         (EXCLUSIVE_OPLOCK|BATCH_OPLOCK)) {
163                         d_printf("EXCLUSIVE+BATCH ");
164                 } else if (e->op_type & EXCLUSIVE_OPLOCK) {
165                         d_printf("EXCLUSIVE       ");
166                 } else if (e->op_type & BATCH_OPLOCK) {
167                         d_printf("BATCH           ");
168                 } else if (e->op_type & LEVEL_II_OPLOCK) {
169                         d_printf("LEVEL_II        ");
170                 } else {
171                         d_printf("NONE            ");
172                 }
173
174                 d_printf(" %s   %s   %s",sharepath, fname, time_to_asc((time_t)e->time.tv_sec));
175         }
176 }
177
178 static void print_brl(struct file_id id,
179                         struct server_id pid, 
180                         enum brl_type lock_type,
181                         enum brl_flavour lock_flav,
182                         br_off start,
183                         br_off size,
184                         void *private_data)
185 {
186         static int count;
187         int i;
188         static const struct {
189                 enum brl_type lock_type;
190                 const char *desc;
191         } lock_types[] = {
192                 { READ_LOCK, "R" },
193                 { WRITE_LOCK, "W" },
194                 { PENDING_READ_LOCK, "PR" },
195                 { PENDING_WRITE_LOCK, "PW" },
196                 { UNLOCK_LOCK, "U" }
197         };
198         const char *desc="X";
199         const char *sharepath = "";
200         char *fname = NULL;
201         struct share_mode_lock *share_mode;
202
203         if (count==0) {
204                 d_printf("Byte range locks:\n");
205                 d_printf("Pid        dev:inode       R/W  start     size      SharePath               Name\n");
206                 d_printf("--------------------------------------------------------------------------------\n");
207         }
208         count++;
209
210         share_mode = fetch_share_mode_unlocked(NULL, id);
211         if (share_mode) {
212                 bool has_stream = share_mode->stream_name != NULL;
213
214                 fname = talloc_asprintf(NULL, "%s%s%s", share_mode->base_name,
215                                         has_stream ? ":" : "",
216                                         has_stream ? share_mode->stream_name :
217                                         "");
218         } else {
219                 fname = talloc_strdup(NULL, "");
220                 if (fname == NULL) {
221                         return;
222                 }
223         }
224
225         for (i=0;i<ARRAY_SIZE(lock_types);i++) {
226                 if (lock_type == lock_types[i].lock_type) {
227                         desc = lock_types[i].desc;
228                 }
229         }
230
231         d_printf("%-10s %-15s %-4s %-9.0f %-9.0f %-24s %-24s\n", 
232                  procid_str_static(&pid), file_id_string_tos(&id),
233                  desc,
234                  (double)start, (double)size,
235                  sharepath, fname);
236
237         TALLOC_FREE(fname);
238         TALLOC_FREE(share_mode);
239 }
240
241 static int traverse_fn1(const struct connections_key *key,
242                         const struct connections_data *crec,
243                         void *state)
244 {
245         if (crec->cnum == -1)
246                 return 0;
247
248         if (!process_exists(crec->pid) || !Ucrit_checkUid(crec->uid)) {
249                 return 0;
250         }
251
252         d_printf("%-10s   %s   %-12s  %s",
253                  crec->servicename,procid_str_static(&crec->pid),
254                  crec->machine,
255                  time_to_asc(crec->start));
256
257         return 0;
258 }
259
260 static int traverse_sessionid(const char *key, struct sessionid *session,
261                               void *private_data)
262 {
263         fstring uid_str, gid_str;
264
265         if (!process_exists(session->pid)
266             || !Ucrit_checkUid(session->uid)) {
267                 return 0;
268         }
269
270         Ucrit_addPid(session->pid);
271
272         fstr_sprintf(uid_str, "%u", (unsigned int)session->uid);
273         fstr_sprintf(gid_str, "%u", (unsigned int)session->gid);
274
275         d_printf("%-7s   %-12s  %-12s  %-12s (%s)\n",
276                  procid_str_static(&session->pid),
277                  numeric_only ? uid_str : uidtoname(session->uid),
278                  numeric_only ? gid_str : gidtoname(session->gid),
279                  session->remote_machine, session->hostname);
280
281         return 0;
282 }
283
284
285
286
287  int main(int argc, char *argv[])
288 {
289         int c;
290         int profile_only = 0;
291         bool show_processes, show_locks, show_shares;
292         poptContext pc;
293         struct poptOption long_options[] = {
294                 POPT_AUTOHELP
295                 {"processes",   'p', POPT_ARG_NONE,     NULL, 'p', "Show processes only" },
296                 {"verbose",     'v', POPT_ARG_NONE,     NULL, 'v', "Be verbose" },
297                 {"locks",       'L', POPT_ARG_NONE,     NULL, 'L', "Show locks only" },
298                 {"shares",      'S', POPT_ARG_NONE,     NULL, 'S', "Show shares only" },
299                 {"user",        'u', POPT_ARG_STRING,   &username, 'u', "Switch to user" },
300                 {"brief",       'b', POPT_ARG_NONE,     NULL, 'b', "Be brief" },
301                 {"profile",     'P', POPT_ARG_NONE, NULL, 'P', "Do profiling" },
302                 {"profile-rates", 'R', POPT_ARG_NONE, NULL, 'R', "Show call rates" },
303                 {"byterange",   'B', POPT_ARG_NONE,     NULL, 'B', "Include byte range locks"},
304                 {"numeric",     'n', POPT_ARG_NONE,     NULL, 'n', "Numeric uid/gid"},
305                 POPT_COMMON_SAMBA
306                 POPT_TABLEEND
307         };
308         TALLOC_CTX *frame = talloc_stackframe();
309         int ret = 0;
310         struct messaging_context *msg_ctx;
311
312         sec_init();
313         load_case_tables();
314
315         setup_logging(argv[0], DEBUG_STDERR);
316
317         if (getuid() != geteuid()) {
318                 d_printf("smbstatus should not be run setuid\n");
319                 ret = 1;
320                 goto done;
321         }
322
323         pc = poptGetContext(NULL, argc, (const char **) argv, long_options, 
324                             POPT_CONTEXT_KEEP_FIRST);
325
326         while ((c = poptGetNextOpt(pc)) != -1) {
327                 switch (c) {
328                 case 'p':
329                         processes_only = true;
330                         break;
331                 case 'v':
332                         verbose = true;
333                         break;
334                 case 'L':
335                         locks_only = true;
336                         break;
337                 case 'S':
338                         shares_only = true;
339                         break;
340                 case 'b':
341                         brief = true;
342                         break;
343                 case 'u':
344                         Ucrit_addUid(nametouid(poptGetOptArg(pc)));
345                         break;
346                 case 'P':
347                 case 'R':
348                         profile_only = c;
349                         break;
350                 case 'B':
351                         show_brl = true;
352                         break;
353                 case 'n':
354                         numeric_only = true;
355                         break;
356                 }
357         }
358
359         /* setup the flags based on the possible combincations */
360
361         show_processes = !(shares_only || locks_only || profile_only) || processes_only;
362         show_locks     = !(shares_only || processes_only || profile_only) || locks_only;
363         show_shares    = !(processes_only || locks_only || profile_only) || shares_only;
364
365         if ( username )
366                 Ucrit_addUid( nametouid(username) );
367
368         if (verbose) {
369                 d_printf("using configfile = %s\n", get_dyn_CONFIGFILE());
370         }
371
372         if (!lp_load_initial_only(get_dyn_CONFIGFILE())) {
373                 fprintf(stderr, "Can't load %s - run testparm to debug it\n",
374                         get_dyn_CONFIGFILE());
375                 ret = -1;
376                 goto done;
377         }
378
379
380         if (lp_clustering()) {
381                 /*
382                  * This implicitly initializes the global ctdbd
383                  * connection, usable by the db_open() calls further
384                  * down.
385                  */
386                 msg_ctx = messaging_init(NULL, procid_self(),
387                                          event_context_init(NULL));
388                 if (msg_ctx == NULL) {
389                         fprintf(stderr, "messaging_init failed\n");
390                         ret = -1;
391                         goto done;
392                 }
393         }
394
395         if (!lp_load(get_dyn_CONFIGFILE(),False,False,False,True)) {
396                 fprintf(stderr, "Can't load %s - run testparm to debug it\n",
397                         get_dyn_CONFIGFILE());
398                 ret = -1;
399                 goto done;
400         }
401
402         switch (profile_only) {
403                 case 'P':
404                         /* Dump profile data */
405                         return status_profile_dump(verbose);
406                 case 'R':
407                         /* Continuously display rate-converted data */
408                         return status_profile_rates(verbose);
409                 default:
410                         break;
411         }
412
413         if ( show_processes ) {
414                 d_printf("\nSamba version %s\n",samba_version_string());
415                 d_printf("PID     Username      Group         Machine                        \n");
416                 d_printf("-------------------------------------------------------------------\n");
417                 if (lp_security() == SEC_SHARE) {
418                         d_printf(" <processes do not show up in "
419                                  "anonymous mode>\n");
420                 }
421
422                 sessionid_traverse_read(traverse_sessionid, NULL);
423
424                 if (processes_only) {
425                         goto done;
426                 }
427         }
428
429         if ( show_shares ) {
430                 if (verbose) {
431                         d_printf("Opened %s\n", lock_path("connections.tdb"));
432                 }
433
434                 if (brief) {
435                         goto done;
436                 }
437
438                 d_printf("\nService      pid     machine       Connected at\n");
439                 d_printf("-------------------------------------------------------\n");
440
441                 connections_forall_read(traverse_fn1, NULL);
442
443                 d_printf("\n");
444
445                 if ( shares_only ) {
446                         goto done;
447                 }
448         }
449
450         if ( show_locks ) {
451                 int result;
452                 struct db_context *db;
453                 db = db_open(NULL, lock_path("locking.tdb"), 0,
454                              TDB_CLEAR_IF_FIRST|TDB_INCOMPATIBLE_HASH, O_RDONLY, 0);
455
456                 if (!db) {
457                         d_printf("%s not initialised\n",
458                                  lock_path("locking.tdb"));
459                         d_printf("This is normal if an SMB client has never "
460                                  "connected to your server.\n");
461                         exit(0);
462                 } else {
463                         TALLOC_FREE(db);
464                 }
465
466                 if (!locking_init_readonly()) {
467                         d_printf("Can't initialise locking module - exiting\n");
468                         ret = 1;
469                         goto done;
470                 }
471
472                 result = share_mode_forall(print_share_mode, NULL);
473
474                 if (result == 0) {
475                         d_printf("No locked files\n");
476                 } else if (result == -1) {
477                         d_printf("locked file list truncated\n");
478                 }
479
480                 d_printf("\n");
481
482                 if (show_brl) {
483                         brl_forall(print_brl, NULL);
484                 }
485
486                 locking_end();
487         }
488
489 done:
490         TALLOC_FREE(frame);
491         return ret;
492 }