Top Level Namespace

Includes:
REXML, Windows::SystemInfo

Defined Under Namespace

Modules: Crypt, Gtk, IPCalc, Jabber, Net Classes: AboutWindow, App, CanvasMap, ConfigGlobal, ConfigWindow, Contact, Contact_selected_info, CustomMonitoring, CustomPlugin, CustomPluginWindow, DebugWindow, EventWindow, Fog, Host, Interface, IrcBot, JMXRef, JMXRefWindow, JmxAttributeMonitoring, JmxMonitoring, Link, LinkView, Listener, MibBrowser, MsgBuffer, Network, Node, NodeHostProperty, NodeHostView, NodeNetworkProperty, NodeNetworkView, NodeView, OIDRef, OIDRefWindow, SMSController, Service, SnmpAnalyzer, SnmpMonitoring, SnmpTrapCapture, SnmpTrapMonitoring, SnmpTrapRef, SnmpTrapRefWindow, SnmpTrapServer, String, SyslogAnalyzer, SyslogCapture, SyslogMonitoring, SyslogRef, SyslogRefWindow, SyslogServer, TreeNodeWindow, WMIRef, WMIRefWindow, WmiMonitoring, XmppBot

Constant Summary collapse

RMAGICK_BYPASS_VERSION_TEST =

launcher main program

David Maciejak 20030120

true
GNMSLIB =
PIXMAP_PATH =
"#{GNMSLIB}/../pixmap"
SOUND_DIR =
"#{GNMSLIB}/../sound"
SCRIPT_DIR =
"#{GNMSLIB}/../script"
TEST_DIR =
"#{GNMSLIB}/../test"
PLUGIN_DIR =
"#{GNMSLIB}/../plugins"
ROOTMAPADDR =
"0.0.0.0"
ROOTMAPNAME =
"ROOT"
NILMAC =
"00:00:00:00:00:00"
DEFAULT_CLASS_C_NETMASK =
"255.255.255.0"
GNMS_PROJECT_SERVER =
"gnms.rubyforge.org"
GNMS_PROJECT_URL =
""
MAP_SYSLOG_SEV =
"Inner"
SNMPv1 =
"1"
SNMPv2 =
"2c"
HOSTNODE =
'h'
NETWORKNODE =
'n'
CRITICAL =
5
MAJOR =
4
WARNING =
3
MINOR =
2
NORMAL =
1
UNMANAGED =
0
UNKNOWN =
-1
PROJECTNAME =
"GNMS"
AUTHORS =
[ "David Maciejak", "Dylan Yin" ]
DOCUMENTORS =
[]
GNMSPPH =
"just a simple text to badly protect secrets"
GNMSKEY =
1978
CONF_DIR =
"#{homedir}/.#{PROJECTNAME.downcase}/conf"
LOG_DIR =
"#{homedir}/.#{PROJECTNAME.downcase}/log"
SNAPSHOT_DIR =
"#{homedir}/.#{PROJECTNAME.downcase}/snapshot"
PID_FILE =
"#{homedir}/.#{PROJECTNAME.downcase}/#{PROJECTNAME.downcase}.pid"
SQLITE_DB =
"#{CONF_DIR}/gnms.db"
SQLITE_DB_TEST =
"#{CONF_DIR}/gnms-test.db"
IDENT_CONF_FILE =
"#{CONF_DIR}/ident.conf"
GLOBAL_CONF_TEST_FILE =
"#{CONF_DIR}/gnms-test.conf"
GLOBAL_CONF_FILE =
"#{CONF_DIR}/gnms.conf"
OIDREFS_CONF_FILE =
"#{CONF_DIR}/snmp_oidrefs.conf"
SYSLOGREFS_CONF_FILE =
"#{CONF_DIR}/syslog_refs.conf"
SNMPTRAPREFS_CONF_FILE =
"#{CONF_DIR}/snmptrap_refs.conf"
DEFAULTHOSTDBFILE =
"nodedb.xml"
DEFAULTHOSTDB =
"#{CONF_DIR}/#{DEFAULTHOSTDBFILE}"
DB_SCHEMA_VERSION =
2.1
GNMSMAJORVERSION =
2
GNMSMINORVERSION =
1
GNMSTAGVERSION =
1
GNMSVERSION =
"#{GNMSMAJORVERSION}.#{GNMSMINORVERSION}"

Instance Method Summary collapse

Instance Method Details

#add_contact_entryObject



33
34
35
36
37
38
39
40
41
42
43
# File 'lib/gui/sub/contact_frame.rb', line 33

def add_contact_entry()
	add_contact_entry_details(true)
	if @cb_mail
@cb_mail.set_sensitive(@button_mail.active?)
   	@cb_im.set_sensitive(@button_im.active?)
@cb_sms.set_sensitive(@entry_sms_device.text != "")
@entry_mail_button.set_sensitive(@cb_mail.active?)
@entry_im_button.set_sensitive(@cb_im.active?)
@entry_sms_button.set_sensitive(@cb_sms.active?)
	end
end

#add_contact_entry_details(add_boolean, ref = nil) ⇒ Object



49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
# File 'lib/gui/sub/contact_frame.rb', line 49

def add_contact_entry_details(add_boolean, ref=nil)
	window=Gtk::Window.new
	window.set_modal(true)
	lbl="Edit Contact Entry"
	if add_boolean
lbl="Add Contact Entry"
	end

 	window.set_title(lbl)
 	window.set_size_request(460, 380)

	window.signal_connect("key_press_event") {|w,e|
      	if e.keyval == Gdk::Keyval::GDK_Escape
	window.destroy
       end
 	}

	frame = Gtk::Frame::new
	frame.border_width=10
	frame.show
	vbox_root=Gtk::VBox::new
	vbox_root.show
	window.add vbox_root
	vbox_root.add frame

	vbox = Gtk::VBox.new
	vbox.show
	frame.add vbox

	table = Gtk::Table.new(11,2,false)
	table.show

	label_fname = Gtk::Label.new "First Name"
	label_fname.show
	if add_boolean
entry_fname = Gtk::Entry.new			
	else
entry_fname = Gtk::Entry.new	
entry_fname.set_editable false
entry_fname.set_text(ref[0])
	end
	entry_fname.show
	table.attach(label_fname,0,1,0,1)
	table.attach(entry_fname,1,2,0,1)

	label_lname = Gtk::Label.new "Last Name"
	label_lname.show
	if add_boolean
entry_lname = Gtk::Entry.new			
	else
entry_lname = Gtk::Entry.new	
entry_lname.set_editable false
entry_lname.set_text(ref[1])
	end
	entry_lname.show
	table.attach(label_lname,0,1,1,2)
	table.attach(entry_lname,1,2,1,2)

	label_email = Gtk::Label.new "Email"
	label_email.show
	if add_boolean
entry_email = Gtk::Entry.new			
	else
entry_email = Gtk::Entry.new	
entry_email.set_text($contact["#{ref[0]}|#{ref[1]}"].email)
	end
	entry_email.show
	table.attach(label_email,0,1,2,3)
	table.attach(entry_email,1,2,2,3)
	
	label_phone = Gtk::Label.new "Phone"
	label_phone.show
	if add_boolean
entry_phone = Gtk::Entry.new			
	else
entry_phone = Gtk::Entry.new	
entry_phone.set_text($contact["#{ref[0]}|#{ref[1]}"].phone)
	end
	entry_phone.show
	table.attach(label_phone,0,1,3,4)
	table.attach(entry_phone,1,2,3,4)

	label_mobile = Gtk::Label.new "Mobile"
	label_mobile.show
	if add_boolean
entry_mobile = Gtk::Entry.new			
	else
entry_mobile = Gtk::Entry.new	
entry_mobile.set_text($contact["#{ref[0]}|#{ref[1]}"].mobile)
	end
	entry_mobile.show
	table.attach(label_mobile,0,1,4,5)
	table.attach(entry_mobile,1,2,4,5)

	label_pager = Gtk::Label.new "Pager"
	label_pager.show
	if add_boolean
entry_pager = Gtk::Entry.new			
	else
entry_pager = Gtk::Entry.new	
entry_pager.set_text($contact["#{ref[0]}|#{ref[1]}"].pager)
	end
	entry_pager.show
	table.attach(label_pager,0,1,5,6)
	table.attach(entry_pager,1,2,5,6)

	label_im = Gtk::Label.new "IM"
	label_im.show 
	if add_boolean
entry_im = Gtk::Entry.new			
	else
entry_im = Gtk::Entry.new	
entry_im.set_text($contact["#{ref[0]}|#{ref[1]}"].im)
	end
	entry_im.show
	table.attach(label_im,0,1,6,7)
	table.attach(entry_im,1,2,6,7)

	label_title = Gtk::Label.new "Title"
	label_title.show 
	if add_boolean
entry_title = Gtk::Entry.new			
	else
entry_title = Gtk::Entry.new	
entry_title.set_text($contact["#{ref[0]}|#{ref[1]}"].title)
	end
	entry_title.show
	table.attach(label_title,0,1,7,8)
	table.attach(entry_title,1,2,7,8)
	
	label_organization = Gtk::Label.new "Organization"
	label_organization.show 
	if add_boolean
entry_organization = Gtk::Entry.new			
	else
entry_organization = Gtk::Entry.new	
entry_organization.set_text($contact["#{ref[0]}|#{ref[1]}"].organization)
	end
	entry_organization.show
	table.attach(label_organization,0,1,8,9)
	table.attach(entry_organization,1,2,8,9)	

	label_location = Gtk::Label.new "Location"
	label_location.show
	if add_boolean
entry_location = Gtk::Entry.new			
	else
entry_location = Gtk::Entry.new	
entry_location.set_text($contact["#{ref[0]}|#{ref[1]}"].location)
	end
	entry_location.show
	table.attach(label_location,0,1,9,10)
	table.attach(entry_location,1,2,9,10)

	label_note = Gtk::Label.new "Note"
	label_note.show
	if add_boolean
entry_note = Gtk::Entry.new			
	else
entry_note = Gtk::Entry.new	
entry_note.set_text($contact["#{ref[0]}|#{ref[1]}"].note)
	end
	entry_note.show
	table.attach(label_note,0,1,10,11)
	table.attach(entry_note,1,2,10,11)

	bbox =Gtk::HBox::new(FALSE, 10)
	bbox.border_width=10
	bbox.show

	ok_button = Gtk::Button.new(Gtk::Stock::OK)
	ok_button.show
	ok_button.signal_connect("clicked") {
if add_boolean
	#new entry!
		if !Contact::contact_exist?(entry_fname.text(),entry_lname.text())
			Contact::add_contact(entry_fname.text(), entry_lname.text(), entry_email.text(), entry_phone.text(),  entry_mobile.text(),  entry_pager.text(), entry_im.text(), entry_title.text(), entry_organization.text(), entry_location.text(), entry_note.text())
		   iter = @contact_view.model.append
		   iter[0] = entry_fname.text()
		   iter[1] = entry_lname.text()
			window.destroy 
		else
 				dialog = Gtk::MessageDialog.new(window, Gtk::Dialog::DESTROY_WITH_PARENT,
                           Gtk::MessageDialog::ERROR,
                           Gtk::MessageDialog::BUTTONS_OK,
                           "Contact '#{entry_fname.text()} #{entry_lname.text()}' already exists!")
			dialog.run
			dialog.destroy
		end
	else
		#modify existing entry				
		Contact::set_email(entry_fname.text(),entry_lname.text(),entry_email.text())
		Contact::set_phone(entry_fname.text(),entry_lname.text(),entry_phone.text())
		Contact::set_mobile(entry_fname.text(),entry_lname.text(),entry_mobile.text())
		Contact::set_pager(entry_fname.text(),entry_lname.text(),entry_pager.text())
		Contact::set_im(entry_fname.text(),entry_lname.text(),entry_im.text())
		Contact::set_title(entry_fname.text(),entry_lname.text(),entry_title.text())
		Contact::set_organization(entry_fname.text(),entry_lname.text(),entry_organization.text())
		Contact::set_location(entry_fname.text(),entry_lname.text(),entry_location.text())
		Contact::set_note(entry_fname.text(),entry_lname.text(),entry_note.text())
		
	  	# @contact_view.each do |model,path,iter|
		#	if (iter[0] == entry_fname.text()) && (iter[1] == entry_lname.text())
		#		break
		#	end
		#end
		window.destroy 
	end
	}

	cancel_button = Gtk::Button.new(Gtk::Stock::CANCEL)
	cancel_button.show
	cancel_button.signal_connect("clicked") {
window.destroy
	}

	ok_button.set_flags(Gtk::Widget::CAN_DEFAULT)
	bbox.pack_start(ok_button, TRUE, TRUE, 0)
	cancel_button.set_flags(Gtk::Widget::CAN_DEFAULT)
	bbox.pack_start(cancel_button, TRUE, TRUE, 0)		
	vbox.add table
	separator = Gtk::HSeparator::new()
	separator.show
	vbox_root.pack_start(separator, FALSE, TRUE, 0)
	vbox_root.pack_start(bbox, FALSE, TRUE, 0)
	window.show
end

#add_host(ip, mask, map = ROOTMAPADDR) ⇒ Object

add host to a network



447
448
449
450
451
452
453
454
455
456
457
458
459
460
# File 'lib/main.rb', line 447

def add_host(ip, mask, map=ROOTMAPADDR)
  if $host[ip] == nil
    $host[ip]=Host.new(ip, mask, nil, nil, map)
    #we update network host list
    if $network[map]
      $network[map].add_host($host[ip])
      $host[ip].node_view.show() if map==get_map()
      $network[map].update_status()
      $event_win.update_statusbar()
      return true
    end
  end
  return false
end

#add_host_entry_with_map(ip, mask, map) ⇒ Object

Add new lign entry > pixmap & host-ip-button



932
933
934
935
936
937
938
939
940
941
942
943
944
945
# File 'lib/node_listener.rb', line 932

def add_host_entry_with_map (ip, mask, map)
	#if host doesnt exist in array
	$log.debug("begin add_host_entry_with_map: #{ip}, #{mask}, #{map}")
	#test is done in add_network
	add_network(map, mask, get_map())

	if $host[ip] == nil
  		$event_win.add_event(EventWindow::CORE_EVENT_TYPE, "INFO", $host[ip], "Find new host")
		Gtk.thread_protect do
			add_host(ip,mask,map)
		end
	end
	$log.debug("end add_host_entry_with_map")
end

#add_host_rangeObject

window to add a range of host node



374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
# File 'lib/gui/adddelnode.rb', line 374

def add_host_range()
    if $win == nil
  	    return
    end

    addwin=Gtk::Window.new
    addwin.set_transient_for($win)
    addwin.set_title("Node host range adding")
    addwin.set_size_request(350, 150)
    addwin.set_modal(true)

   addwin.signal_connect("key_press_event") {|w,e|
      if e.keyval == Gdk::Keyval::GDK_Escape
			addwin.destroy
      end
    }

    frame = Gtk::Frame::new("Add host range")
    frame.border_width=10
    frame.show
    vbox_root=Gtk::VBox::new
    vbox_root.show
    addwin.add vbox_root
    vbox_root.add frame
    vbox = Gtk::VBox.new
    vbox.show
    frame.add vbox

    table = Gtk::Table.new(3,2,false)
    table.show

    hostalivetoo = Gtk::CheckButton.new("Add alive hosts in range")
    hostalivetoo.show

    label_ip = Gtk::Label.new "IP"
    label_ip.show

    hbox = Gtk::HBox.new
    hbox.show
    entry_ip = Gtk::Entry.new
	 entry_ip.show
    entry_ip_end = Gtk::Entry.new
	 entry_ip_end.set_size_request(10,-1)
	 entry_ip_end.show
	 hbox.add entry_ip
	 hbox.add entry_ip_end

    table.attach(label_ip,0,1,0,1)
    table.attach(hbox,1,2,0,1)

    ok_button = Gtk::Button.new(Gtk::Stock::OK)
    ok_button.show
    ok_button.signal_connect("clicked") {

    if isValidIPv4(entry_ip.text) && isInteger(entry_ip_end.text)

       if hostalivetoo.active?
    	   tfindrangeremotehost(entry_ip.text, entry_ip_end.text)
       else
	    	lentry=entry_ip.text.split(/\./)
			ip_addr="#{lentry[0]}.#{lentry[1]}.#{lentry[3]}."	
			limit_inf=lentry[3].to_i()
			limit_sup=entry_ip_end.text.to_i()
			if limit_inf > limit_sup
				limit_tmp=limit_inf
				limit_inf=limit_sup
				limit_sup=limit_tmp
			end
			for ip in limit_inf..limit_sup
 	   		add_host(ip_addr+"#{ip}", 24, get_map())
			end
			#$network[get_map()].update_status()
       end
       addwin.destroy 
    else
		 if isInteger(entry_ip_end.text)
  	    	errorEntry(addwin, entry_ip.text)
		 else
  	    	errorEntry(addwin, entry_ip_end.text)
		 end
    end
    }

    cancel_button = Gtk::Button.new(Gtk::Stock::CANCEL)
    cancel_button.show
    cancel_button.signal_connect("clicked") {
  	    addwin.destroy 
    }

	 bbox =Gtk::HBox::new(FALSE, 10)
	 bbox.border_width=10
	 bbox.show

	 ok_button.set_flags(Gtk::Widget::CAN_DEFAULT)
	 bbox.pack_start(ok_button, TRUE, TRUE, 0)
	 cancel_button.set_flags(Gtk::Widget::CAN_DEFAULT)
	 bbox.pack_start(cancel_button, TRUE, TRUE, 0)

	 vbox.add(table)
	 vbox.add hostalivetoo
	 separator = Gtk::HSeparator::new()
	 separator.show
	 vbox_root.pack_start(separator, FALSE, TRUE, 0)
	 vbox_root.pack_start(bbox, FALSE, TRUE, 0)

    addwin.show
end

#add_monitoring_thread(str, thr) ⇒ Object

add a thread identified by a corresponding str name



250
251
252
253
254
255
256
257
258
259
260
261
262
# File 'lib/main.rb', line 250

def add_monitoring_thread(str, thr)
  $log.debug("Starting thread #{str}")
  if thr
    $thread_list[str]=thr
    if thr.class == Thread
      $threads.add(thr)
    else
      $log.error("Thread #{str} could not be loaded")      
    end
  else
    $log.debug("Thread #{str} not started")  
  end
end

#add_network(ip, mask, map) ⇒ Object

add a network need: ip, mask, map



493
494
495
496
497
498
499
500
501
502
503
# File 'lib/main.rb', line 493

def add_network(ip, mask, map)
  if map != nil && $network[ip] == nil && $host[ip] == nil
    $network[ip]=Network.new(ip, mask, nil, nil, map)
    $network[ip].node_view.show() if map==get_map()
    #add network in network map
    $network[map].add_network($network[ip])
    return true
  end
  $log.error("IP addr #{ip} already in use") if map != nil
  return false
end

#add_node_def_exception_list(str) ⇒ Object

add node definition to exception list it could be an ip or a regex



95
96
97
98
99
# File 'lib/main.rb', line 95

def add_node_def_exception_list(str)
  if !$node_exception_list.include?(str)
    $node_exception_list.push(str)
  end
end

#addhostentry(ip, mask, map = nil, mac = nil, avail = nil) ⇒ Object

Add new lign entry > pixmap & host-ip-button



950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
# File 'lib/node_listener.rb', line 950

def addhostentry(ip, mask, map=nil, mac=nil, avail=nil)
	#if host doesnt exist in array
	if $host[ip] == nil
		$event_win.add_event(EventWindow::CORE_EVENT_TYPE, "INFO", $host[ip], "Find new host")
		Gtk.thread_protect do
		  if map
			  add_host(ip, mask, map)
      else
			  add_host(ip, mask)
			end
      if !mac.nil?
        $host[ip].mac = mac
      end
      if !avail.nil?
        $host[ip].set_avail_severity(avail)
      end
		end
	end
end

#addnetworkwinObject

window to add a network



485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
# File 'lib/gui/adddelnode.rb', line 485

def addnetworkwin()
  if $win == nil
    return
  end

  addwin=Gtk::Window.new
  addwin.set_transient_for($win)
  addwin.set_title("Node network adding")
  addwin.set_size_request(350, 200)
  addwin.set_modal(true)

  addwin.signal_connect("key_press_event") {|w,e|
    if e.keyval == Gdk::Keyval::GDK_Escape
      addwin.destroy
    end
  }

  frame = Gtk::Frame::new("Add Network")
  frame.border_width=10
  frame.show
  vbox_root=Gtk::VBox::new
  vbox_root.show
  addwin.add vbox_root
  vbox_root.add frame
  vbox = Gtk::VBox.new
  vbox.show
  frame.add vbox

  table = Gtk::Table.new(3,2,false)
  table.show

  hostalivetoo = Gtk::CheckButton.new("Add alive host in network")
  hostalivetoo.show

  label_ip = Gtk::Label.new "IP / Domain"
  label_ip.show
  entry_ip = Gtk::Entry.new
  entry_ip.show

  table.attach(label_ip,0,1,0,1)
  table.attach(entry_ip,1,2,0,1)
  label_netmask = Gtk::Label.new "Netmask"
  label_netmask.show

  hbox = Gtk::HBox.new
  hbox.show
  entry_netmask = Gtk::Entry.new
  entry_netmask.set_text DEFAULT_CLASS_C_NETMASK
  entry_netmask.set_editable false
  entry_netmask.show

  adj = Gtk::Adjustment::new(0, 1.0, 32.0, 1.0, 5.0, 0.0)
  compressnetmask = Gtk::SpinButton::new(adj, 0, 0)
  compressnetmask.set_wrap(true)
  compressnetmask.set_editable false
  compressnetmask.set_value 24.0

  compressnetmask.show
  hbox.add entry_netmask
  hbox.add compressnetmask
  table.attach(label_netmask,0,1,1,2)
  table.attach(hbox,1,2,1,2)

  entry_ip.signal_connect("changed") {
    if entry_ip.text.match /^[\.\d]+$/
      hbox.set_sensitive(true)
    else
      hbox.set_sensitive(false)
    end
  }

  compressnetmask.signal_connect("value-changed") {
    entry_netmask.set_text bit2netmask(compressnetmask.value_as_int)
  }

  ok_button = Gtk::Button.new(Gtk::Stock::OK)
  ok_button.show
  ok_button.signal_connect("clicked") {
    if isValidIPv4(entry_ip.text)
      lentry=entry_ip.text.split(/\./)
      if !$network[entry_ip.text]
        if hostalivetoo.active?
          tfindremotehost(entry_ip.text,compressnetmask.value_as_int)
        else
          add_network(entry_ip.text, compressnetmask.value_as_int, get_map())
        end
        addwin.destroy
      else
        errorEntry(addwin, "Network already exists")
      end
    else
      #it may be a domainname
      ip_from_domain = ""
      begin
        ip_from_domain = Resolv.getaddress entry_ip.text
        #transfor this ip in at least a class C
        ip_from_domain.gsub! /\.\d+$/,".0"
      rescue Exception => msg
        errorEntry(addwin, msg)
        next
      end
      if !$network[ip_from_domain]
        add_network(ip_from_domain, 24, get_map())
      else
        errorEntry(addwin, "Network already exists")
      end
      if hostalivetoo.active?
        dns = Resolv::DNS.new
        
        resource_type=Resolv::DNS::Resource::IN::ANY
        if RUBY_VERSION.match("^1\.8")
          #only A type for ruby 1.8 as ANY is not working
          resource_type=Resolv::DNS::Resource::IN::A
        end
        
        dns.getresources(entry_ip.text, resource_type).collect do |r|
          if r.kind_of?(Resolv::DNS::Resource::IN::MX) or r.kind_of?(Resolv::DNS::Resource::IN::A) or r.kind_of?(Resolv::DNS::Resource::IN::AAAA) or r.kind_of?(Resolv::DNS::Resource::IN::NS) then
            begin
              ip_from_name = ""
	      name = ""
              if r.kind_of?(Resolv::DNS::Resource::IN::MX)
	        name = r.exchange.to_s.strip
                ip_from_name = Resolv.getaddress name
              elsif r.kind_of?(Resolv::DNS::Resource::IN::A)
                ip_from_name = r.address.to_s.strip
              elsif r.kind_of?(Resolv::DNS::Resource::IN::NS)
	        name = r.name.to_s.strip
                ip_from_name = Resolv.getaddress name
              end
              if !$host[ip_from_name]
                add_host(ip_from_name, 24, ip_from_domain)
		if $host[ip_from_name]
		  if r.kind_of?(Resolv::DNS::Resource::IN::MX)
		    $host[ip_from_name].add_service("tcp", 25, "", 0, 0)
		  elsif r.kind_of?(Resolv::DNS::Resource::IN::NS)
		    $host[ip_from_name].add_service("udp", 53, "", 0, 0)		  
		  end
		  if name != ""
		    $host[ip_from_name].dns_name = name
		  end
		end
              else
                errorEntry(addwin, "Host already exists")
              end
            rescue Exception => msg
              errorEntry(addwin, msg)
              next
            end
          end
        end
      end
      addwin.destroy
    end
  }

  cancel_button = Gtk::Button.new(Gtk::Stock::CANCEL)
  cancel_button.show
  cancel_button.signal_connect("clicked") {
    addwin.destroy
  }

  bbox =Gtk::HBox::new(FALSE, 10)
  bbox.border_width=10
  bbox.show

  ok_button.set_flags(Gtk::Widget::CAN_DEFAULT)
  bbox.pack_start(ok_button, TRUE, TRUE, 0)
  cancel_button.set_flags(Gtk::Widget::CAN_DEFAULT)
  bbox.pack_start(cancel_button, TRUE, TRUE, 0)

  vbox.add(table)
  vbox.add hostalivetoo
  separator = Gtk::HSeparator::new()
  separator.show
  vbox_root.pack_start(separator, FALSE, TRUE, 0)
  vbox_root.pack_start(bbox, FALSE, TRUE, 0)

  addwin.show
end

#addnodewinObject

window to add an host



106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
# File 'lib/gui/adddelnode.rb', line 106

def addnodewin()

  if $win == nil
    return
  end

  addwin=Gtk::Window.new
  addwin.set_transient_for($win)
  addwin.set_title("Node host adding")
  addwin.set_size_request(350, 270)
  addwin.set_modal(true)

  addwin.signal_connect("key_press_event") {|w,e|
    if e.keyval == Gdk::Keyval::GDK_Escape
      addwin.destroy
    end
  }

  frame = Gtk::Frame::new("Add an host")
  frame.border_width=10
  frame.show
  vbox_root=Gtk::VBox::new
  vbox_root.show
  addwin.add vbox_root
  vbox_root.add frame

  vbox = Gtk::VBox.new
  vbox.show
  frame.add vbox

  table = Gtk::Table.new(8,2,false)
  table.show

  label_icon = Gtk::Label.new "Icon"
  label_icon.show

  ent =  Gtk::ImageComboList.new("type", "host")
  ent.show

  table.attach(label_icon,0,1,0,1)
  table.attach(ent,1,2,0,1)

  #set_editable set_visibility set_sensitive set_text
  entry_ip = Gtk::Entry.new
  entry_ip.show

  label_ip = Gtk::Label.new "IP"
  label_ip.show

  table.attach(label_ip,0,1,1,2)
  table.attach(entry_ip,1,2,1,2)

  hbox = Gtk::HBox.new
  hbox.show
  entry_netmask = Gtk::Entry.new
  entry_netmask.set_text DEFAULT_CLASS_C_NETMASK
  entry_netmask.set_editable false
  entry_netmask.show

  adj = Gtk::Adjustment::new(0, 1.0, 32.0, 1.0, 5.0, 0.0)
  compressnetmask = Gtk::SpinButton::new(adj, 0, 0)
  compressnetmask.set_wrap(true)
  compressnetmask.set_editable false
  compressnetmask.set_value 24.0

  compressnetmask.show
  hbox.add entry_netmask
  hbox.add compressnetmask
  label_netmask = Gtk::Label.new "Mask"
  label_netmask.show
  table.attach(label_netmask,0,1,2,3)
  table.attach(hbox,1,2,2,3)

  compressnetmask.signal_connect("value-changed") {
    entry_netmask.set_text bit2netmask(compressnetmask.value_as_int)
  }

  entry_name = Gtk::Entry.new
  #entry_name.select_region(0, 5)
  entry_name.show

  label_name = Gtk::Label.new "DNS name"
  label_name.show

  table.attach(label_name,0,1,3,4)
  table.attach(entry_name,1,2,3,4)

  label_map = Gtk::Label.new "Map"
  label_map.show
  entry_map = Gtk::ComboBox.new
  get_network().each { |n|
    entry_map.append_text(n)
  }
  if get_map() != nil
    ind = get_network().index(get_map())
    entry_map.set_active(ind) if ind
  end
  entry_map.show

  table.attach(label_map,0,1,4,5)
  table.attach(entry_map,1,2,4,5)

  entry_description = Gtk::Entry.new
  #entry_description.select_region(0, 5)
  entry_description.show
  label_description = Gtk::Label.new "Description"
  label_description.show

  table.attach(label_description,0,1,5,6)
  table.attach(entry_description,1,2,5,6)

  bbox =Gtk::HBox::new(FALSE, 10)
  bbox.border_width=10
  bbox.show

  ok_button = Gtk::Button.new(Gtk::Stock::OK)
  ok_button.show
  ok_button.signal_connect("clicked") {
    nnode_pix_os = "os/unknown.png"
    if ent.filename == nil
      nnode_type = "pc"
    else
      nnode_type_t = ent.filename.match('^.+\/(.+)\..*$')
      nnode_type=nnode_type_t[1]
    end

    if isValidIPv4(entry_ip.text) or (entry_name.text != "")
      if (entry_ip.text == "") and (entry_name.text != "")
        #we will try to resolve the name
        ip_from_name = ""
        begin
          ip_from_name = Resolv.getaddress entry_name.text
        rescue Exception => msg
          errorEntry(addwin, msg)
          next
        end
        entry_ip.text = ip_from_name if ip_from_name
      end
      if entry_name.text == ""
        entry_name.set_text Node::NONAME_PROPERTY
      end

      if entry_description.text == ""
        entry_description.set_text Node::NODESCR_PROPERTY
      end

      lentry=entry_ip.text.split(/\./)
      if lentry[3] == "0" || lentry[3] == "255"
        #add a network
        $log.info("Seems that it's a network! Trying to add it")
        mask=compressnetmask.value_as_int
        tfindremotehost(entry_ip.text,mask)
        addwin.destroy
      else
        if !$host[entry_ip.text]
          #we dont use add_host, here we can set more attribute
          $host[entry_ip.text]=Host.new(entry_ip.text,compressnetmask.value_as_int,nil,nil,entry_map.active_text,Node::NOARP_PROPERTY,entry_name.text,Node::NONAME_PROPERTY,nil,UNKNOWN,0,0, nnode_pix_os,entry_description.text,nnode_type,"unknown")
          $network[entry_map.active_text].add_host($host[entry_ip.text])
          $network[entry_map.active_text].update_status()
          $host[entry_ip.text].reload()
          #now we need to force node view drawing
          $host[entry_ip.text].node_view.show() if entry_map.active_text==get_map()
          $event_win.add_event(EventWindow::CORE_EVENT_TYPE, "INFO", $host[entry_ip.text], "Host added")
          #$network[entry_map.active_text].update_status()
          addwin.destroy
        else
          errorEntry(addwin, "Host already exists")
        end
      end
    else
      errorEntry(addwin, entry_ip.text)
    end
  }

  cancel_button = Gtk::Button.new(Gtk::Stock::CANCEL)
  cancel_button.show
  cancel_button.signal_connect("clicked") {
    addwin.destroy
  }

  ok_button.set_flags(Gtk::Widget::CAN_DEFAULT)
  bbox.pack_start(ok_button, TRUE, TRUE, 0)
  cancel_button.set_flags(Gtk::Widget::CAN_DEFAULT)
  bbox.pack_start(cancel_button, TRUE, TRUE, 0)

  vbox.add(table)
  separator = Gtk::HSeparator::new()
  separator.show
  vbox_root.pack_start(separator, FALSE, TRUE, 0)
  vbox_root.pack_start(bbox, FALSE, TRUE, 0)


  addwin.show
end

#alarm_beepObject



77
78
79
# File 'lib/notify/alarm.rb', line 77

def alarm_beep()
  printf "\a"
end

#alarm_handle(src_module, category, ip_str, summary, datetime) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/notify/alarm.rb', line 10

def alarm_handle(src_module, category, ip_str, summary, datetime)
  $log.debug("in alarm_handle")
  if $config.level != nil && ($LEVEL.index(category)>=$LEVEL.index($config.level))
    i=0
    level_alert_type=$level_alert_type
    if $host[ip_str] && (!$network[$host[ip_str].map].inherit_from_global)
      level_alert_type=$network[$host[ip_str].map].alert_type_by_level
    end
    level_alert_type[category].each do |alert|
      if alert == true
        case i
        when 0 then #MAIL
          alarm_mail("#{datetime} #{ip_str} #{summary}", ip_str, "#{src_module}", category)
        when 1 then #POPUP
          alarm_popup("#{src_module} #{datetime} #{ip_str} #{summary}")
        when 2 then #BEEP
          if $host[ip_str] && (!$network[$host[ip_str].map].inherit_from_global)
            if $network[$host[ip_str].map].sound_file_path_by_level[category] != nil
              if !$sound_is_played
                Thread.start { alarm_sound($network[$host[ip_str].map].sound_file_path_by_level[category]) }
              end
            else
              alarm_beep()
            end
          else
            if $config.sound_file_path_by_level[category] != nil
              if !$sound_is_played
                Thread.start { alarm_sound($config.sound_file_path_by_level[category]) }
              end
            else
              alarm_beep()
            end
          end
        when 3 then #SYSLOG
          text=sprintf("module='%s', severity='%s', time='%s', src='%s', descr='%s'", src_module, category, datetime, ip_str, summary)
          alarm_syslog(text)
        when 4 then #SMS / PAGER
          if ($config.sms_device != "") && ($config.sms_device != nil)
            if $host[ip_str] && (!$network[$host[ip_str].map].inherit_from_global) && ($network[$host[ip_str].map].sms_num_by_level[category] != "") && ($network[$host[ip_str].map].sms_num_by_level[category] != nil)
              alarm_sms($config.sms_device,$network[$host[ip_str].map].sms_num_by_level[category],"#{src_module} #{datetime} #{ip_str} #{summary}")
            elsif ($config.sms_num_by_level[category] != "") && ($config.sms_num_by_level[category] != nil)
              alarm_sms($config.sms_device,$config.sms_num_by_level[category],"#{src_module} #{datetime} #{ip_str} #{summary}")
            end
          end
        when 5 then #IM
          if $host[ip_str] && (!$network[$host[ip_str].map].inherit_from_global) && ($network[$host[ip_str].map].im_dest_by_level[category] != "") && ($network[$host[ip_str].map].im_dest_by_level[category] != nil)
            alarm_xmpp($network[$host[ip_str].map].im_dest_by_level[category],"#{src_module} #{datetime} #{ip_str} #{summary}")
          elsif ($config.im_dest_by_level[category] != "") && ($config.im_dest_by_level[category] != nil)
            alarm_xmpp($config.im_dest_by_level[category],"#{src_module} #{datetime} #{ip_str} #{summary}")
          end
        when 6 then #SCRIPT EXECUTION
          if $host[ip_str] && (!$network[$host[ip_str].map].inherit_from_global) && ($network[$host[ip_str].map].script_name_by_level[category] != "") && ($network[$host[ip_str].map].script_name_by_level[category] != nil)
            alarm_script($network[$host[ip_str].map].script_name_by_level[category], ip_str)
          elsif ($config.script_name_by_level[category] != "") && ($config.script_name_by_level[category] != nil)
            alarm_script($config.script_name_by_level[category], ip_str)
          else
            $log.error("Invalid script name for #{category}")
          end
        when 7 then #IRC
          alarm_irc("date=#{datetime} src=#{ip_str} descr=#{summary}")
        end
      end
      i+=1
    end
  end
end

#alarm_irc(txt) ⇒ Object



245
246
247
# File 'lib/notify/alarm.rb', line 245

def alarm_irc(txt)
  $irc_daemon.add_in_queue(txt) if $irc_daemon
end

#alarm_mail(msg, ip, src_module = nil, sev = INFO) ⇒ Object



166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
# File 'lib/notify/alarm.rb', line 166

def alarm_mail(msg, ip, src_module=nil, sev=INFO)
  if src_module != "core"

    mail_server_addr=$config.mail_server_addr
    mail_server_port=$config.mail_server_port

    tmail_receipt=$config.mail_by_level[sev]
    if $host[ip] && (!$network[$host[ip].map].inherit_from_global)
      tmail_receipt=$network[$host[ip].map].mail_by_level[sev]
    end

    Thread.start {

      tmail_receipt.each{|contact|
        mail_dst=Contact::get_contact_email(contact.firstname, contact.lastname)
        if mail_dst != ""
          begin
            Net::SMTP.start( mail_server_addr, mail_server_port ) {|smtp|
              smtp.send_mail <<EndOfMail, "root@localhost", "#{mail_dst}"
              From: gnms admin <#{ENV["USER"]}@localhost>
              To: gnms contact <#{Contact::get_contact_email(contact.firstname, contact.lastname)}>
              Subject: gnms notification

              #{msg}
EndOfMail

            }
          rescue Exception => msg
            $log.error("Error #{sev} severity level #{msg} when sending mail to '#{mail_dst}' on '#{mail_server_addr}'/'#{mail_server_port}'")
          end

        else
          $log.error("Mail contact empty for #{contact.firstname} #{contact.lastname}")
        end
      }
    }

  end
end

#alarm_popup(text) ⇒ Object



152
153
154
155
156
157
158
159
160
161
162
163
164
# File 'lib/notify/alarm.rb', line 152

def alarm_popup(text)
  if $win.visible?
    dialog = Gtk::MessageDialog.new($win, Gtk::Dialog::MODAL,
    Gtk::MessageDialog::INFO,
    Gtk::MessageDialog::BUTTONS_OK,
    text)
    dialog.signal_connect('response') { dialog.destroy }
    dialog.show
  elsif $icon.embedded?
    #window is hidden and trayicon exists so we just blink the icon
    $icon.set_blinking(true)
  end
end

#alarm_script(command, ip) ⇒ Object



206
207
208
209
210
211
212
# File 'lib/notify/alarm.rb', line 206

def alarm_script(command, ip)
  if !FileTest.exist?("#{SCRIPT_DIR}/#{command}")
    $log.error("Invalid script path name #{SCRIPT_DIR}/#{command}")
  else
    `#{SCRIPT_DIR}/#{command} #{ip}`
  end
end

#alarm_sms(device, tnumber, txt) ⇒ Object



214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
# File 'lib/notify/alarm.rb', line 214

def alarm_sms(device, tnumber, txt)
  if $defined_lib_sms == false
    $log.error("Can't send SMS, notification type is disabled cause a library is missing")
  else
    Thread.start {
      tnumber.each{|contact|
        sms=Contact::get_contact_mobile(contact.firstname, contact.lastname)
        if sms != ""
          mySMS = SMSController.new(device, sms, txt)
          mySMS.sendSMS
        else
          $log.error("SMS contact empty for #{contact.firstname} #{contact.lastname}")
        end
      }
    }
  end
end

#alarm_sound(sound_file) ⇒ Object



81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
# File 'lib/notify/alarm.rb', line 81

def alarm_sound(sound_file)
  if $sound_is_played
    return
  end

  if !FileTest.exist?("#{SOUND_DIR}/#{sound_file}")
    $log.error("Sound file not found at #{SOUND_DIR}/#{sound_file}")
    alarm_beep()
    return
  end

  if $defined_lib_gst
    $sound_is_played = true
      #create the pipeline
      pipeline = Gst::Pipeline.new
      # create a disk reader
      filesrc = Gst::ElementFactory.make("filesrc")
      filesrc.location = "#{SOUND_DIR}/#{sound_file}"

      decoder = Gst::ElementFactory.make("decodebin")

      if decoder == nil
	$log.error("gstreamer issue when initializing sound env")
	return
      end

      audio_convert = Gst::ElementFactory.make("audioconvert")
      audio_resample = Gst::ElementFactory.make("audioresample")
      audio_sink = Gst::ElementFactory.make("autoaudiosink")
      pipeline.add(filesrc, decoder, audio_convert, audio_resample, audio_sink)

      # link elements
      filesrc >> decoder
      audio_convert >> audio_resample >> audio_sink

      decoder.signal_connect("new-decoded-pad") do |element, pad|
	sink_pad = audio_convert["sink"]
	pad.link(sink_pad)
      end
            
      reading = true
      bus = pipeline.bus
      bus.add_watch do |bus, message|
	case message.type
	when Gst::Message::EOS
	  $sound_is_played = false
	  reading = false
	when Gst::Message::ERROR
	  #p message.parse
	  $sound_is_played = false
	  reading = false
	end
	true
      end

      # start playing
      pipeline.play
      while(reading) do 
        sleep(1)
      end
      pipeline.stop
      pipeline.set_state(Gst::State::NULL)
  else
    $log.error("Sound can't be played as sound lib gstreamer is not available")   
  end
end

#alarm_syslog(text) ⇒ Object



148
149
150
# File 'lib/notify/alarm.rb', line 148

def alarm_syslog(text)
  Syslog.log(Syslog::LOG_WARNING, text)
end

#alarm_xmpp(im_dest_addr, txt) ⇒ Object



232
233
234
235
236
237
238
239
240
241
242
243
# File 'lib/notify/alarm.rb', line 232

def alarm_xmpp(im_dest_addr, txt)
  if $im_daemon
    im_dest_addr.each{|contact|
      im=Contact::get_contact_im(contact.firstname, contact.lastname)
      if im != ""
        $im_daemon.add_in_queue(im, txt)
      else
        $log.error("IM contact empty for #{contact.firstname} #{contact.lastname}")
      end
    }
  end
end

#bit2netmask(int) ⇒ Object

convert bitmask address to netmask address



679
680
681
682
683
684
# File 'lib/cmd_parse.rb', line 679

def bit2netmask(int)
  if int==0
    return "0.0.0.0"
  end
  return IPCalc.bits_to_netmask(int)
end

#blowfish_decode(str) ⇒ Object

decode the given str using blowfish crypto algo



152
153
154
155
156
157
158
159
160
# File 'lib/main.rb', line 152

def blowfish_decode(str)
  begin
    blowfish = Crypt::Blowfish.new(GNMSPPH)
    return blowfish.decrypt_string(str)
  rescue
    $log.debug("error when blowfish decoding")
  end
  return ""
end

#blowfish_encode(str) ⇒ Object

encode the given str using blowfish crypto algo



139
140
141
142
143
144
145
146
147
# File 'lib/main.rb', line 139

def blowfish_encode(str)
  begin
    blowfish = Crypt::Blowfish.new(GNMSPPH)
    return blowfish.encrypt_string(str)
  rescue
    $log.debug("error when blowfish encoding")
  end
  return ""
end

#broadcast_pingObject

ping broadcast



222
223
224
225
226
227
# File 'lib/cmd_parse.rb', line 222

def broadcast_ping
	ipbroadcast=`#{$config.ping_path} 255.255.255.255 -b -c 2 -n 2>&1 | grep ^64 | awk '{ print $4 }'`
	ipbroadcast.gsub!(":","")
	iptab=ipbroadcast.split(/\n/)
	return iptab
end

#broadcast_remote_ping(network, mask) ⇒ Object

Return all host seems to be up (responding to icmp) from a given network (class c) netmork submitted as 0.0.0.0/24



549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
# File 'lib/cmd_parse.rb', line 549

def broadcast_remote_ping(network, mask)
  $log.debug "cmd_parse broadcast_remote_ping #{network} #{mask}"
  puts "cmd_parse broadcast_remote_ping #{network} #{mask}"
  result=[]
  if $config.nmap_path == ""
    return result
  end
  res=nil
  nmap_version = $config.nmap_vers.to_f()
  case 
  when nmap_version >= 6.0 then 
     res=`#{$config.nmap_path} --send-ip -PE -sP -n "#{network}/#{mask}"  2>/dev/null| grep "^Nmap scan report.*$" | awk '{print $5}'`
  when nmap_version >= 4.0 then
	 res=`#{$config.nmap_path} --send-ip -PE -sP -n "#{network}/#{mask}"  2>/dev/null| grep "^H.*appears.*$" | awk '{print $2}'`
  else
	 res=`#{$config.nmap_path} -PE -sP -n "#{network}/#{mask}"  2>/dev/null| grep "^H.*$" | awk '{print $2}'`
  end
  if res
	  lres=res.split(/\n/)
	  for ip in lres
	    result.push ip unless ip == network    
	  end
  end
  return result
end

#busy?Boolean

Returns:

  • (Boolean)


1082
1083
1084
# File 'lib/main.rb', line 1082

def busy?()
   return $win.busy?()
end

#cell_edited(cell, path_string, new_text, col) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/gui/sub/account_frame.rb', line 12

def cell_edited(cell, path_string, new_text, col, node)
	iter = @account_view.model.get_iter(path_string)
	#check if account id does not already exist for the host
	if (node.ip != ROOTMAPADDR) && (iter[0] != "snmp")	
  #None is a special entry
  if (col == 0) && ((node.(new_text)) || (new_text.upcase == "NONE") || (new_text.upcase == ""))
   return	
  end
  #we have to store the modified value
  if col == 0
   , password = node.(iter[0])
   node.(iter[0])		
   node.(new_text, , password)
  elsif col == 1
   node.(iter[0], new_text)
  elsif col == 2
   node.(iter[0], new_text)
  end
  iter[col] = new_text
	else
errorEntry(@window, "'snmp' account has to be configured in Option>Preference>SNMP tab")
	end
end

#check_contact_value(hash) ⇒ Object



691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
# File 'lib/main.rb', line 691

def check_contact_value(hash)
hash_bck=Hash.new
hash.each_key {|id|
  hash_bck[id]=hash[id].dup unless !hash[id]
}
hash.each_pair{|key, value|
  if key != nil
    value.each {|contact|
      if !Contact::contact_exist?(contact.firstname, contact.lastname)
        #contact does not exist anymore
        hash_bck[key].delete(contact)
      else
        #contact exist so we set it "in-use"
        Contact::add_use(contact.firstname, contact.lastname)
      end
      } unless !value
    end
  }
  return hash_bck
end

#check_scanner_versionObject



920
921
922
923
924
925
926
927
928
929
930
931
# File 'lib/main.rb', line 920

def check_scanner_version()
  if $config.nmap_path
    $config.nmap_vers=nmap_version()
    if $config.nmap_vers == nil
      $log.warn("You should install NMAP version from http://www.insecure.org/nmap/ to access full scan features")
    else
      if  $config.nmap_vers.to_i() < 4
        $log.info("You should update NMAP to latest version from http://www.insecure.org/nmap/")
      end
    end
  end
end

#check_update_windowObject

check new update from the main home project url



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
# File 'lib/gui/update_window.rb', line 31

def check_update_window
  last_version_file_name="lastversion"
  window = Gtk::Window.new
  window.set_size_request(500,250)
  window.set_title "Check update"
  window.set_transient_for($win)

  vbox = Gtk::VBox.new
  vbox.show
  window.add vbox

  begin
    Net::HTTP.version_1_1
  rescue
  end
  last_version=""
  text = Gtk::TextView.new
  combo_last_version = Gtk::ComboBox.new
  Thread.start {

  		begin
		Gtk.thread_protect do
			$win.hide_update_menu_entry()
		end
 		Net::HTTP.start(GNMS_PROJECT_SERVER, 80) do |http|
   	 	 response,=http.get('/'+GNMS_PROJECT_URL+'/'+last_version_file_name)
		 response.body.each do |str|
		  re=Regexp.new('^(\d+)\.(\d+)\.?(.+)?$')
		  str.scan(re) do |m1, m2, m3|
			  if (m1.to_i() > GNMSMAJORVERSION)
		  			  last_version=last_version+"#{str}"
			  elsif (m1.to_i() >= GNMSMAJORVERSION) && (m2.to_i() > GNMSMINORVERSION)
		  			  last_version=last_version+"#{str}"
			  elsif (m1.to_i() >= GNMSMAJORVERSION) && (m2.to_i() >= GNMSMINORVERSION)
				  if m3 != nil
					  if m3 > GNMSTAGVERSION
			  			  last_version=last_version+"#{str}"
					  end
				  end
			  end
		  end
		 end
		 Gtk.thread_protect do
		 hbox=Gtk::HBox.new
		 labelf=Gtk::Label.new("Choose version")
		 hbox.add labelf
                 last_version.split(/\n/).each {|v|
                   combo_last_version.append_string(v)
                 }
		 combo_last_version.show
		 hbox.add combo_last_version
		 vbox.add hbox
		  combo_last_version.signal_connect("changed") {|val|
			 if val.text != ""
				 text.buffer.delete(text.buffer.start_iter,text.buffer.end_iter)
				 text.buffer.insert_at_cursor(get_changelog(combo_last_version.active_text).to_s)
			 end
		  }
		 end
	 	end
	 rescue
		  #no update available
  		  Gtk.thread_protect do
			  window.set_size_request(350,25)
			  label=Gtk::Label.new("No update available for version : "+GNMSVERSION)
			  vbox.add label
		  end
     	end
	Gtk.thread_protect do
	 if last_version != ""
		changelog=get_changelog(combo_last_version.active_text)
		text.cursor_visible=false
		text.set_size_request(-1,225)
		text.set_editable(false)
		text.show
		scrolled_window = Gtk::ScrolledWindow.new(nil, nil)
		scrolled_window.border_width=2
		scrolled_window.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC)  
		scrolled_window.show
		scrolled_window.add(text)
		text.grab_focus
		text.freeze
		text.buffer.insert_at_cursor(changelog.to_s)
		vbox.add scrolled_window
	 end
	 window.show_all
	 window.signal_connect("key_press_event") {|w,e|
		if e.keyval == Gdk::Keyval::GDK_Escape
   	  window.destroy
		end
	 }
	 window.signal_connect("destroy") {|w,e|
		  $win.show_update_menu_entry()
	 }
	 end
  }
end

#choose_network_map(node_ip, default_map = nil) ⇒ Object

window to ask in which map to add a node, list networks in combobox return the network ip



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# File 'lib/gui/adddelnode.rb', line 10

def choose_network_map(node_ip, default_map=nil)
  $in_network_map_choice.synchronize {
    choosemap_win = Gtk::Window.new
    choosemap_win.set_transient_for($win)
    choosemap_win.set_title("Choose network map")
    choosemap_win.set_size_request(500, 200)
    choosemap_win.set_modal(true)

    hbox=Gtk::HBox::new   
    frame = Gtk::Frame::new
    frame.border_width=10
    frame.show
    hbox.add frame

    hbox_root=Gtk::HBox::new
    vbox = Gtk::VButtonBox::new

    label_map = Gtk::Label.new "New node at IP #{node_ip} found in local network segment.\nWhere do you want to add it ?"
    entry_map = Gtk::ComboBox.new
    get_network().each { |n|
      entry_map.append_text(n)
    }
    entry_map.prepend_text("Exception list")
    entry_map.set_active(1)
    if !default_map.nil? and !default_map.empty?
      ind = get_network().index(default_map)
      entry_map.set_active(ind) if ind
    end
    bbox=Gtk::HButtonBox.new  
    ok_button = Gtk::Button.new(Gtk::Stock::OK)
    ok_button.signal_connect("clicked") {
      result = entry_map.active_text
      choosemap_win.destroy
      $network_map_result = result
    }
    cancel_button = Gtk::Button.new(Gtk::Stock::CANCEL)
    cancel_button.signal_connect("clicked") {
      choosemap_win.destroy
      $network_map_result = ""
    }
    
    choosemap_win.signal_connect("key_press_event") {|w,e|
    if e.keyval == Gdk::Keyval::GDK_Escape
      choosemap_win.destroy
      $network_map_result = ""
    end
    }
    
    check_map = Gtk::CheckButton.new("Always map to this network")
    if $network_map_always == 1
      check_map.set_active true
    else
      check_map.set_active false    
    end
    check_map.signal_connect("toggled") {
      # we don't care of the box is checked when the map is set to exception
        $network_map_always = check_map.active? ? 1 : 0        
    }
    
    bbox.add ok_button
    bbox.add cancel_button
    bbox.show_all

    vbox.add label_map
    vbox.add entry_map
    vbox.add check_map
    vbox.add bbox
    hbox_root.add Gtk::Image.new(Gtk::Stock::DIALOG_QUESTION, Gtk::IconSize::DIALOG)
    hbox_root.add vbox
    frame.add hbox_root
    choosemap_win.add hbox
    choosemap_win.show_all
  }
end

#close_dbObject

close sqlite database



41
42
43
# File 'lib/node_db.rb', line 41

def close_db()
	$db.close
end

#confirm_exit_windowObject

popup to confirm application exit



278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
# File 'lib/main.rb', line 278

def confirm_exit_window()
  $in_confirm_exit_window=true
  if $config.confirm_quit
    dialog = Gtk::MessageDialog.new($win, Gtk::Dialog::DESTROY_WITH_PARENT,
    Gtk::MessageDialog::QUESTION,
    Gtk::MessageDialog::BUTTONS_YES_NO,
    "Do you really want to quit ?")
    dialog.run do |r|
      dialog.destroy
      if r == Gtk::Dialog::RESPONSE_NO then
        $in_confirm_exit_window=false
        return true
      else
        return false
      end
    end
  else
    return false
  end
end

#contain(iplocal) ⇒ Object

To know if we already know this ip



918
919
920
921
922
923
924
925
926
927
# File 'lib/node_listener.rb', line 918

def contain(iplocal)
	i=0
	$host.each_key{|ip|	
		if ip == iplocal
			return i
		end
	i=i+1
	}
return -1
end

#create_db(fic = SQLITE_DB) ⇒ Object

create database tables



1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
# File 'lib/node_db.rb', line 1466

def create_db(fic=SQLITE_DB)
	$log.info("Create and fill DB")
	open_db(fic)
	begin
	sql = <<SQL
	

		CREATE TABLE service_monitor (
			id INTEGER NOT NULL,
			node_id INTEGER
				CONSTRAINT fk_node_id REFERENCES node(id),
			service_id INTEGER
				CONSTRAINT fk_service_id REFERENCES service(id),
			monitor INTEGER,
			service_sev INTEGER,
			PRIMARY KEY (id, node_id, service_id)
		);

		CREATE TABLE service (
			id INTEGER NOT NULL PRIMARY KEY,
			protocol VARCHAR(10),
			port INTEGER,
			name VARCHAR(50)
		);

		CREATE TABLE snmp_monitor (
			id INTEGER NOT NULL PRIMARY KEY,
			snmp_state BOOLEAN,
			oid_ref_name VARCHAR(50)
				CONSTRAINT fk_oid_ref_name REFERENCES oid_ref(name),				
			oper INTEGER,
			threshold INTEGER,
			oidsev INTEGER
		);

		CREATE TABLE node_and_snmp_monitor(
			id INTEGER NOT NULL,
			node_id INTEGER
				CONSTRAINT fk_node_id REFERENCES node(id),
			snmp_monitor_id INTEGER
				CONSTRAINT fk_snmp_monitor_id REFERENCES snmp_monitor(id),
			PRIMARY KEY (id, node_id, snmp_monitor_id)
		);

		CREATE TABLE wmi_monitor (
			id INTEGER NOT NULL PRIMARY KEY,
			wmi_state BOOLEAN,
			wmi_ref_name VARCHAR(50)
				CONSTRAINT fk_wmi_ref_name REFERENCES wmi_ref(name),				
			oper INTEGER,
			value INTEGER,
			wmisev INTEGER
		);

		CREATE TABLE jmx_monitor (
			id INTEGER NOT NULL PRIMARY KEY,
			jmx_state BOOLEAN,
			jmx_ref_name VARCHAR(50)
				CONSTRAINT fk_jmx_ref_name REFERENCES jmx_ref(name),
			jmx_protocol VARCHAR(10),
			jmx_port INTEGER,
			jmx_auth VARCHAR(20)
		);

		CREATE TABLE jmx_attr_monitor (
			id INTEGER NOT NULL PRIMARY KEY,
			name VARCHAR(50),
			oper INTEGER,
			value INTEGER,
			jmxsev INTEGER
		);

		CREATE TABLE node_and_wmi_monitor(
			id INTEGER NOT NULL,
			node_id INTEGER
				CONSTRAINT fk_node_id REFERENCES node(id),
			wmi_monitor_id INTEGER
				CONSTRAINT fk_wmi_monitor_id REFERENCES wmi_monitor(id),
			PRIMARY KEY (id, node_id, wmi_monitor_id)
		);

		CREATE TABLE node_and_jmx_monitor(
			id INTEGER NOT NULL,
			node_id INTEGER
				CONSTRAINT fk_node_id REFERENCES node(id),
			jmx_monitor_id INTEGER
				CONSTRAINT fk_jmx_monitor_id REFERENCES jmx_monitor(id),
			jmx_attr_monitor_id INTEGER
				CONSTRAINT fk_jmx_attr_monitor_id REFERENCES jmx_attr_monitor(id),
			PRIMARY KEY (id, node_id, jmx_monitor_id, jmx_attr_monitor_id)
		);

		CREATE TABLE snmptrap_monitor (
			id INTEGER NOT NULL PRIMARY KEY,
			snmptrap_state BOOLEAN,
			snmptrap_ref VARCHAR(50)
				CONSTRAINT fk_snmptrap_ref_name REFERENCES snmptrap_ref(name),	
			snmptrap_sev INTEGER
		);

		CREATE TABLE node_and_snmptrap_monitor(
			id INTEGER NOT NULL,
			node_id INTEGER
				CONSTRAINT fk_node_id REFERENCES node(id),
			snmptrap_monitor_id INTEGER
				CONSTRAINT fk_snmptrap_id REFERENCES snmptrap(id),
			PRIMARY KEY (id, node_id, snmptrap_monitor_id)
		);

		CREATE TABLE syslog_monitor (
			id INTEGER NOT NULL PRIMARY KEY,
			syslog_state BOOLEAN,
			syslog_ref VARCHAR(50)
				CONSTRAINT fk_syslog_ref_name REFERENCES syslog_ref(name),				
			syslog_sev INTEGER
		);

		CREATE TABLE node_and_syslog_monitor(
			id INTEGER NOT NULL,
			node_id INTEGER
				CONSTRAINT fk_node_id REFERENCES node(id),
			syslog_monitor_id INTEGER
				CONSTRAINT fk_syslog_monitor_id REFERENCES syslog_monitor(id),
			PRIMARY KEY (id, node_id, syslog_monitor_id)
		);

		CREATE TABLE custom_monitor(
			id INTEGER NOT NULL PRIMARY KEY,
      custom_name VARCHAR(50)      
		);
    
    CREATE TABLE node_and_custom_monitor(
			id INTEGER NOT NULL,
			node_id INTEGER
				CONSTRAINT fk_node_id REFERENCES node(id),
			custom_monitor_id INTEGER
				CONSTRAINT fk_custom_monitor_id REFERENCES custom_monitor(id),
      custom_state BOOLEAN,
      custom_param VARCHAR(512),
      custom_sev INTEGER,      
			PRIMARY KEY (id, node_id, custom_monitor_id)
		);    
    
		CREATE TABLE account (
			id INTEGER PRIMARY KEY,
			idname VARCHAR(50),
			login VARCHAR(50),
			password VARCHAR(50)
		);

		CREATE TABLE node_and_account (
			id INTEGER NOT NULL,
			node_id INTEGER
				CONSTRAINT fk_node_id REFERENCES node(id),
			account_id INTEGER
				CONSTRAINT fk_account_id REFERENCES account(id),
			PRIMARY KEY (id, node_id, account_id)
		);

		CREATE TABLE alert_override (
			id INTEGER PRIMARY KEY,
			node_id INTEGER
				CONSTRAINT fk_node_id REFERENCES node(id),
			alert_override_detail_id INTEGER
				CONSTRAINT fk_alert_override_detail_id REFERENCES alert_override_detail(id),
			alert_type_by_level VARCHAR(20)
		);
		
		CREATE TABLE alert_override_contact (
			id INTEGER PRIMARY KEY,
			contact_id INTEGER
				CONSTRAINT fk_contact REFERENCES contact(id)
		);
		
		CREATE TABLE alert_override_detail (
			id INTEGER PRIMARY KEY,
			mail_state BOOLEAN,
			mail_by_level_id INTEGER
				CONSTRAINT fk_alert_override_contact1 REFERENCES alert_override_contact(id),
			popup_state BOOLEAN,
			beep_state BOOLEAN,
			sound_file_path_by_level VARCHAR(255),
			syslog_state BOOLEAN,
			sms_state BOOLEAN,
			sms_num_by_level_id INTEGER
				CONSTRAINT fk_alert_override_contact2 REFERENCES alert_override_contact(id),
			im_state BOOLEAN,
			im_dest_by_level_id INTEGER
				CONSTRAINT fk_alert_override_contact3 REFERENCES alert_override_contact(id),
			script_state BOOLEAN,
			script_name_by_level VARCHAR(255),
			irc_state BOOLEAN
		);

		CREATE TABLE interface (
			id INTEGER NOT NULL PRIMARY KEY,
			name VARCHAR(10),
			link_status INTEGER,
			speed VARCHAR(50),
			type VARCHAR(50)
		);

		CREATE TABLE node_and_interface (
			id INTEGER NOT NULL,
			node_id INTEGER
				CONSTRAINT fk_node_id REFERENCES node(id),
			interface_id INTEGER
				CONSTRAINT fk_interface_id REFERENCES interface(id),
			PRIMARY KEY (id, node_id, interface_id)
		);

		CREATE TABLE node (    
			id INTEGER NOT NULL PRIMARY KEY,
                        uuid VARCHAR(36),
			nodetype VARCHAR(1),
			ip VARCHAR(15),
			netmask INTEGER,
			ipv6 VARCHAR(39),
			netmask6 INTEGER,
			mac VARCHAR(17),
			map INTEGER
				CONSTRAINT fk_node_id REFERENCES node(id),
			status INTEGER,
			avail_sev INTEGER,
			snmp_sev INTEGER,
			custom_sev INTEGER,
			trap_sev INTEGER,
                        service_sev INTEGER,
                        wmi_sev INTEGER,
                        syslog_sev INTEGER,
                        jmx_sev INTEGER,
                        service_monitor_id INTEGER
				CONSTRAINT fk_service_monitor_id REFERENCES service_monitor(id),
			node_and_snmp_monitor_id INTEGER
				CONSTRAINT fk_node_and_snmp_monitor_id REFERENCES node_and_snmp_monitor(id),
			node_and_wmi_monitor_id INTEGER
				CONSTRAINT fk_node_and_wmi_monitor_id REFERENCES node_and_wmi_monitor(id),
			node_and_jmx_monitor_id INTEGER
				CONSTRAINT fk_node_and_jmx_monitor_id REFERENCES node_and_jmx_monitor(id),
			node_and_snmptrap_monitor_id INTEGER
				CONSTRAINT fk_node_and_snmptrap_monitor_id REFERENCES node_and_snmptrap_monitor(id),
			node_and_syslog_monitor_id INTEGER
				CONSTRAINT fk_node_and_syslog_monitor_id REFERENCES node_and_syslog_monitor(id),
      node_and_custom_monitor_id INTEGER
				CONSTRAINT fk_node_and_custom_monitor_id REFERENCES node_and_custom_monitor(id),			      
      node_and_account_id INTEGER CONSTRAINT fk_node_and_account_id REFERENCES node_and_account(id),
			node_and_group_id INTEGER CONSTRAINT fk_node_and_group_id REFERENCES node_and_group(id),
			node_and_interface_id INTEGER CONSTRAINT fk_node_and_interface_id REFERENCES node_and_interface(id),
			x INTEGER,
			y INTEGER,
			icon VARCHAR(50),
			description VARCHAR(255),
			snmp_version VARCHAR(50),
			snmp_port VARCHAR(50),
			snmp_timeout VARCHAR(50),
			snmp_retry VARCHAR(50),
			type VARCHAR(50),
			os VARCHAR(50),
			name VARCHAR(50),
			dns_name VARCHAR(50),
			dns_domain VARCHAR(50),
			netbios_name VARCHAR(50),
			netbios_domain VARCHAR(50),
			node_size INTEGER,
			map_bg_type VARCHAR(20),
			map_bg_data VARCHAR(255)
		);

		CREATE TABLE link (
			id INTEGER PRIMARY KEY,
			link_state INTEGER,
			name VARCHAR(255),
			speed VARCHAR(50),
			node1 INTEGER
				CONSTRAINT fk_node_id REFERENCES node(id),	
			node2 INTEGER
				CONSTRAINT fk_node_id REFERENCES node(id)
		);

		CREATE TABLE ngroup (
			id INTEGER PRIMARY KEY,
			name VARCHAR(50)
		);

		CREATE TABLE node_and_group (		
			id INTEGER NOT NULL,
			node_id INTEGER
				CONSTRAINT fk_node_id REFERENCES node(id),
			group_id INTEGER
				CONSTRAINT fk_group_id REFERENCES ngroup(id),
			PRIMARY KEY (id, node_id, group_id)
		);

		CREATE TABLE node_and_contact (		
			id INTEGER NOT NULL,
			node_id INTEGER
				CONSTRAINT fk_node_id REFERENCES node(id),
			contact_id INTEGER
				CONSTRAINT fk_contact_id REFERENCES contact(id),
			PRIMARY KEY (id, node_id, contact_id)
		);

		CREATE TABLE contact (		
			id INTEGER NOT NULL,
			firstname VARCHAR(50),
			lastname VARCHAR(50),
			email VARCHAR(50),
			phone VARCHAR(20),
			mobile VARCHAR(20),
			pager VARCHAR(20),
			im VARCHAR(50),
			title VARCHAR(255),
			organization VARCHAR(255),
			location VARCHAR(255),
			note VARCHAR(255),
			PRIMARY KEY (id)
		);
		
		CREATE TABLE db_schema (
			version REAL
		);
		
		INSERT INTO db_schema VALUES (#{DB_SCHEMA_VERSION});
		
		CREATE TABLE oid_ref (
			name VARCHAR(50) PRIMARY KEY,
			description VARCHAR(255),
			value VARCHAR(255)
		);

		INSERT INTO oid_ref VALUES ('Cpu', 'UCD-SNMP-MIB::ssCpuUser.0+UCD-SNMP-MIB::ssCpuSystem.0', '1.3.6.1.4.1.2021.11.9.0+1.3.6.1.4.1.2021.11.10.0');

		CREATE TABLE wmi_ref (
			name VARCHAR(50) PRIMARY KEY,
			description VARCHAR(255),
			value VARCHAR(255)
		);

		INSERT INTO wmi_ref VALUES ('Services', 'List Win32 Started Services', 'select Name from Win32_Service where Started=true');
		INSERT INTO wmi_ref VALUES ('Processes', 'List Win32 Processes', 'select * from Win32_Process');
		INSERT INTO wmi_ref VALUES ('Accounts', 'List Win32 Accounts', 'select * from Win32_UserAccount');

		CREATE TABLE jmx_ref (
			name VARCHAR(50) PRIMARY KEY,
			description VARCHAR(255),
			mbean VARCHAR(255),
			attribute VARCHAR(255)
		);
		INSERT INTO jmx_ref VALUES ('Memory', 'Memory MBean', 'java.lang:type=Memory', 'heap_memory_usage non_heap_memory_usage');
		INSERT INTO jmx_ref VALUES ('OS', 'OS MBean', 'java.lang:type=OperatingSystem', 'name');
		INSERT INTO jmx_ref VALUES ('Thread', 'Thread MBean', 'java.lang:type=Threading', 'thread_count');

		CREATE TABLE syslog_ref (
			name VARCHAR(50) PRIMARY KEY,
			description VARCHAR(255),
			value VARCHAR(255)
		);
		INSERT INTO syslog_ref VALUES ('Catch all', 'Trigger on all events', '(.+)');

		CREATE TABLE snmptrap_ref (
			name VARCHAR(50) PRIMARY KEY,
			description VARCHAR(255),
			value VARCHAR(255)
		);
		INSERT INTO snmptrap_ref VALUES ('Cold Start', '', 'snmp.0.0');
		INSERT INTO snmptrap_ref VALUES ('Warn Start', '', 'snmp.1.0');
		INSERT INTO snmptrap_ref VALUES ('Link Down', '', 'snmp.2.0');
		INSERT INTO snmptrap_ref VALUES ('Link Up', '', 'snmp.3.0');
		INSERT INTO snmptrap_ref VALUES ('Authentication failure', '', 'snmp.4.0');

SQL

			$db.execute_batch(sql)
			File.chmod(0600, fic)
		rescue SQLite3::SQLException => msg
			$log.fatal("Error #{msg} #{msg.backtrace.join("\n")}, can't create DB #{fic}")
			File.delete(fic)
			exit(1)
		end
		db_read_refs()
    db_set_custom_monitor()
end

#create_root_networkObject



2322
2323
2324
2325
2326
2327
2328
# File 'lib/node_db.rb', line 2322

def create_root_network()
    $log.info("Creating root network")
    if !exist_network(ROOTMAPADDR)
       $network[ROOTMAPADDR]=Network.new(ROOTMAPADDR)
       $network[ROOTMAPADDR].name="Root"
    end
end

#create_uuidObject

return a version 4 UUID it’s std lib in ruby 1.9



125
126
127
128
129
130
131
132
133
134
# File 'lib/main.rb', line 125

def create_uuid()
  if (defined?(SecureRandom.uuid))
    SecureRandom.uuid
  else
    ary = SecureRandom.random_bytes(16).unpack("NnnnnN")
    ary[2] = (ary[2] & 0x0fff) | 0x4000
    ary[3] = (ary[3] & 0x3fff) | 0x8000
    "%08x-%04x-%04x-%04x-%04x%08x" % ary
  end
end

#db_add_account(ip, nodetype, accounts) ⇒ Object

add an account to a specific node



520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
# File 'lib/node_db.rb', line 520

def (ip, nodetype, accounts)
	nodeid=db_get_node_id(ip, nodetype)
	nodeaccountid=(nodeid)
	if nodeaccountid == 0
			stmt=$db.prepare("UPDATE node SET node_and_account_id=(SELECT IFNULL(MAX(id),0) FROM node_and_account)+1 WHERE id=?")
			begin
				$db.transaction
				stmt.execute(nodeid)
				$db.commit
			rescue
				$log.error("error updating node_and_account_id table")
			end
			nodeaccountid=(nodeid)
	end
	if nodeaccountid != 0
		 = 1
		stmt2=$db.prepare("SELECT IFNULL(MAX(id),0)+1 AS cid FROM account")		
		rs = stmt2.execute
		 =  rs.first.join("\t").to_s.to_i
		stmt3=$db.prepare("INSERT INTO account VALUES (?, ?, ?, ?)")
		stmt4=$db.prepare("INSERT INTO node_and_account VALUES (?, ?, ?)")
	        $db.transaction
	        accounts.each { |idname, , passwd|
	          password=Base64.encode64(Fog.new(passwd,GNMSKEY))
		  stmt3.execute(, idname, , password)
		  stmt4.execute(nodeaccountid, nodeid, )
		   +=1
		}
		$db.commit
	else
		$log.error("db_add_account: something goes wrong trying to find the account id")
		return
	end
end

#db_add_custom_monitoring(ip, nodetype, custom_mon_array) ⇒ Object

add a custom monitoring for specific node



339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
# File 'lib/node_db.rb', line 339

def db_add_custom_monitoring(ip, nodetype, custom_mon_array)
  #here custom_monitor table is up to date
	nodeid=db_get_node_id(ip, nodetype)
	nodecustommonitoringid=db_get_node_custom_monitor_id(nodeid)
	if nodecustommonitoringid == 0
			   stmt=$db.prepare("UPDATE node SET node_and_custom_monitor_id=(SELECT IFNULL(MAX(id),0) FROM node_and_custom_monitor)+1 WHERE id=?")
				$db.transaction
				stmt.execute(nodeid)
				$db.commit
				nodecustommonitoringid=db_get_node_custom_monitor_id(nodeid)
	end

	if nodecustommonitoringid != 0
  	  stmt2=$db.prepare("SELECT id FROM custom_monitor WHERE custom_name = ?")
	  stmt4=$db.prepare("INSERT INTO node_and_custom_monitor VALUES (?, ?, ?, ?, ?, ?)")
	  $db.transaction
	  custom_mon_array.each {|state, name, param, sev|
		stmt2.execute(name) do |rs|		
			rs.each do |customnonid|
				stmt4.execute(nodecustommonitoringid, nodeid, customnonid, state, param, sev)
			end
		end
	  }
	  $db.commit
	else
		$log.error("db_add_custom_monitoring: something goes wrong trying to add the custom monitoring id")
		return
	end
end

#db_add_interface(ip, nodetype, name, lstatus, sp, tp) ⇒ Object

add an interface to a specific node



559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
# File 'lib/node_db.rb', line 559

def db_add_interface(ip, nodetype, name, lstatus, sp, tp)
	nodeid=db_get_node_id(ip, nodetype)
	nodeinterfaceid=db_get_node_interface_id(nodeid)
	if nodeinterfaceid == 0
			stmt=$db.prepare("UPDATE node SET node_and_interface_id=(SELECT IFNULL(MAX(id),0) FROM node_and_interface)+1 WHERE id=?")
			begin
				$db.transaction
				stmt.execute(nodeid)
				$db.commit
			rescue
				$log.error("error updating node_and_interface_id table")
			end
			nodeinterfaceid=db_get_node_interface_id(nodeid)
	end

	if nodeinterfaceid != 0
		stmt2=$db.prepare("SELECT IFNULL(MAX(id),0)+1 FROM interface")
		stmt2.execute do |rs|
			rs.each do |interfaceid|
				$db.transaction
				stmt3=$db.prepare("INSERT INTO interface VALUES (?, ?, ?, ?, ?)")
				stmt3.execute(interfaceid, name, lstatus, sp, tp)
				stmt4=$db.prepare("INSERT INTO node_and_interface VALUES (?, ?, ?)")
				stmt4.execute(nodeinterfaceid, nodeid, interfaceid)
				$db.commit
			end
		end			
	else
		$log.error("db_add_interface: something goes wrong trying to find the interface id")
		return
	end	
end

#db_add_jmx_monitoring(ip, nodetype, state, ref_name, proto, port, auth, attr_h) ⇒ Object



440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
# File 'lib/node_db.rb', line 440

def db_add_jmx_monitoring(ip, nodetype, state, ref_name, proto, port, auth, attr_h)
	nodeid=db_get_node_id(ip, nodetype)
	nodejmxmonitoringid=db_get_node_jmx_monitor_id(nodeid)
	if nodejmxmonitoringid == 0
		stmt=$db.prepare("UPDATE node SET node_and_jmx_monitor_id=(SELECT IFNULL(MAX(id),0) FROM node_and_jmx_monitor)+1 WHERE id=?")
		$db.transaction
		stmt.execute(nodeid)
		$db.commit
		nodejmxmonitoringid=db_get_node_jmx_monitor_id(nodeid)
	end

	if nodejmxmonitoringid != 0
		stmt2=$db.prepare("SELECT IFNULL(MAX(id),0)+1 FROM jmx_monitor")
		stmt2.execute do |rs|
			rs.each do |jmxmonid|
				$db.transaction
				stmt3=$db.prepare("INSERT INTO jmx_monitor VALUES (?, ?, ?, ?, ?, ?)")
				stmt3.execute(jmxmonid, state, ref_name, proto, port, auth)
				
				stmt4=$db.prepare("SELECT IFNULL(MAX(id),0)+1 FROM jmx_attr_monitor")
				stmt4.execute do |rs|
					rs.each do |jmxattrmonid|
						stmt5=$db.prepare("INSERT INTO jmx_attr_monitor VALUES (?, ?, ?, ?, ?)")
						attr_h.each_value {|attr|
							stmt5.execute(jmxattrmonid, attr.attributeName, attr.operator, attr.value, attr.severity)
						}
						stmt6=$db.prepare("INSERT INTO node_and_jmx_monitor VALUES (?, ?, ?, ?)")
						stmt6.execute(nodejmxmonitoringid, nodeid, jmxmonid, jmxattrmonid)
						$db.commit
					end
				end
			end
		end
	else
		$log.error("db_add_jmx_monitoring: something goes wrong trying to find the jmx monitoring id")
		return
	end
end

#db_add_service(ip, nodetype, proto, number, name, monitor_flag, sev) ⇒ Object



369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
# File 'lib/node_db.rb', line 369

def db_add_service(ip, nodetype, proto, number, name, monitor_flag, sev)
	serv_id=db_get_service_id(proto, number)
	if serv_id == 0
		stmt=$db.prepare("INSERT INTO service VALUES (NULL, ?, ?, ?)")
		$db.transaction
		stmt.execute(proto, number, name)
		$db.commit
		serv_id=db_get_service_id(proto, number)
	end

	#add the monitoring in service_monitor table
	if serv_id != 0
	   #request service monitor id	
	   stmt=$db.prepare("SELECT id, service_monitor_id FROM node WHERE ip=? and nodetype=?")
	   stmt.execute(ip, nodetype) do |rs|
	      rs.each do |hid,smid|
		      if !smid
			      stmt2=$db.prepare("INSERT INTO service_monitor VALUES ((SELECT IFNULL(MAX(id),0) FROM service_monitor)+1, ?, ?, ?, ?)")
			      $db.transaction
			      begin
				      stmt2.execute(hid, serv_id, monitor_flag, sev)
			      rescue
				      $log.error("error inserting in db_add_service #{hid} #{serv_id} #{monitor_flag} #{sev}")
			      end
					

			      stmt3=$db.prepare("SELECT distinct(id) FROM service_monitor WHERE node_id=? and service_id=?")
			      stmt3.execute(hid, serv_id) do |rs|
				      rs.each do |field,type|
					      stmt4=$db.prepare("UPDATE node SET service_monitor_id=? WHERE id=?")
					      begin
					      	stmt4.execute(field, hid)
					      rescue
				  	        $log.error("error updating in db_add_service #{field} #{hid}")
					      end
				      end		
			      end
			      $db.commit
		      else
			      stmt2=$db.prepare("INSERT INTO service_monitor VALUES (?, ?, ?, ?, ?)")
				begin
			      $db.transaction		
			      stmt2.execute(smid, hid, serv_id, monitor_flag, sev)
			      $db.commit
				rescue
				  $log.error("error inserting in db_add_service #{smid} #{hid} #{serv_id} #{monitor_flag} #{sev}")
				end
		      end
	      end
	   end
	else
		$log.error("db_add_service: something goes wrong trying to find the service id")
	end
end

#db_add_snmp_monitoring(ip, nodetype, state, ref_name, op, val, sev) ⇒ Object



424
425
426
# File 'lib/node_db.rb', line 424

def db_add_snmp_monitoring(ip, nodetype, state, ref_name, op, val, sev)
	db_add_template_monitoring("snmp", ip, nodetype, state, ref_name, op, val, sev)
end

#db_add_snmptrap_monitoring(ip, nodetype, state, ref_name, sev) ⇒ Object



432
433
434
# File 'lib/node_db.rb', line 432

def db_add_snmptrap_monitoring(ip, nodetype, state, ref_name, sev)
	db_add_template_monitoring("snmptrap", ip, nodetype, state, ref_name, sev)
end

#db_add_syslog_monitoring(ip, nodetype, state, ref_name, sev) ⇒ Object



436
437
438
# File 'lib/node_db.rb', line 436

def db_add_syslog_monitoring(ip, nodetype, state, ref_name, sev)
	db_add_template_monitoring("syslog", ip, nodetype, state, ref_name, sev)
end

#db_add_template_monitoring(templ, ip, nodetype, state, oidref_name, op, val = nil, sev = nil) ⇒ Object

template to add a monitoring to a specific node



482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
# File 'lib/node_db.rb', line 482

def db_add_template_monitoring(templ, ip, nodetype, state, oidref_name, op, val=nil, sev=nil)
	nodeid=db_get_node_id(ip, nodetype)
	nodesnmpmonitoringid=eval "db_get_node_#{templ}_monitor_id(nodeid)"
	if nodesnmpmonitoringid == 0
			   stmt=$db.prepare("UPDATE node SET node_and_#{templ}_monitor_id=(SELECT IFNULL(MAX(id),0) FROM node_and_#{templ}_monitor)+1 WHERE id=?")
				$db.transaction
				stmt.execute(nodeid)
				$db.commit
				nodesnmpmonitoringid=eval "db_get_node_#{templ}_monitor_id(nodeid)"
	end

	if nodesnmpmonitoringid != 0
		stmt2=$db.prepare("SELECT IFNULL(MAX(id),0)+1 FROM #{templ}_monitor")
		stmt2.execute do |rs|
			rs.each do |snmpmonid|
				$db.transaction
				if !sev
					#we are in snmptrap or syslog monitoring
					stmt3=$db.prepare("INSERT INTO #{templ}_monitor VALUES (?, ?, ?, ?)")
					stmt3.execute(snmpmonid, state, oidref_name, op)
				else
					stmt3=$db.prepare("INSERT INTO #{templ}_monitor VALUES (?, ?, ?, ?, ?, ?)")
					stmt3.execute(snmpmonid, state, oidref_name, op, val, sev)
				end
				stmt4=$db.prepare("INSERT INTO node_and_#{templ}_monitor VALUES (?, ?, ?)")
				stmt4.execute(nodesnmpmonitoringid, nodeid, snmpmonid)
				$db.commit
			end
		end
	else
		$log.error("db_add_#{templ}_monitoring: something goes wrong trying to find the #{templ} monitoring id")
		return
	end
end

#db_add_wmi_monitoring(ip, nodetype, state, ref_name, op, val, sev) ⇒ Object



428
429
430
# File 'lib/node_db.rb', line 428

def db_add_wmi_monitoring(ip, nodetype, state, ref_name, op, val, sev)
	db_add_template_monitoring("wmi", ip, nodetype, state, ref_name, op, val, sev)
end

#db_check_version_schemaObject

read db schema version



1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
# File 'lib/node_db.rb', line 1359

def db_check_version_schema()
	stmt=$db.prepare("SELECT version FROM db_schema")
        stmt.execute() do |rs|
	    rs.each do |vers|
	       #converting SQLite3::ResultSet::ArrayWithTypesAndFields to float
	       if vers.join("\t").to_s.to_f != DB_SCHEMA_VERSION
	       	      $log.fatal("Wrong db version #{vers} expected #{DB_SCHEMA_VERSION}, backup your .db file and try again")
	              exit()
	       end
	    end
	end
        return 0	
end

#db_del_accounts(node_ip, node_type) ⇒ Object

remove all accounts stuff for a specific node



699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
# File 'lib/node_db.rb', line 699

def db_del_accounts(node_ip, node_type)
	stmt=$db.prepare("SELECT id, node_and_account_id FROM node WHERE ip=? and nodetype=?")
 	stmt.execute(node_ip,node_type) do |rs|
		rs.each do |nodeid,nodeaccountid|
			if nodeaccountid
				stmt=$db.prepare("SELECT distinct account_id FROM node_and_account WHERE node_id=? and id=?")
		 		stmt.execute(nodeid, nodeaccountid) do |rs|
					rs.each do |accountid|
						if accountid
							stmt2=$db.prepare("DELETE from account WHERE id=?")
			      				$db.transaction
					 		stmt2.execute(accountid)
							$db.commit
						end
					end
					stmt3=$db.prepare("DELETE from node_and_account WHERE node_id=? and id=?")
			      		$db.transaction
					stmt3.execute(nodeid,nodeaccountid)
					$db.commit										
				end
			end	
		end
	end
end

#db_del_alert_override(node_ip, node_type = nil) ⇒ Object

remove all alert override for a specific node



889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
# File 'lib/node_db.rb', line 889

def db_del_alert_override(node_ip, node_type=nil)
	if !node_type
		node_type=NETWORKNODE
	end
	nid=db_get_node_id(node_ip, node_type)
	stmt=$db.prepare("SELECT alert_override_detail_id FROM alert_override WHERE node_id=?")
	stmt.execute(nid) do |rs|
		rs.each do |aoid|
			
			stmt2=$db.prepare("SELECT mail_by_level_id, sms_num_by_level_id, im_dest_by_level_id FROM alert_override_detail WHERE id=?")
			stmt2.execute(aoid) do |rs|
				rs.each do |mail_contact_id, sms_contact_id, im_contact_id|
					stmt3=$db.prepare("DELETE from alert_override_contact WHERE id=?")
					$db.transaction
					stmt3.execute(mail_contact_id)
					stmt3.execute(sms_contact_id)
					stmt3.execute(im_contact_id)
					$db.commit
				end
			end			
			stmt4=$db.prepare("DELETE from alert_override_detail WHERE id=?")
			$db.transaction
			stmt4.execute(aoid)
			$db.commit
		end
	end
	stmt5=$db.prepare("DELETE from alert_override WHERE node_id=?")
	$db.transaction
	stmt5.execute(nid)
	$db.commit	
end

#db_del_contact(firstname, lastname) ⇒ Object

del contacts information we don’t need to check for node_and_contact value entries, they should have already been handled so here we remove not USED contact



1435
1436
1437
1438
1439
1440
# File 'lib/node_db.rb', line 1435

def db_del_contact(firstname, lastname)
	stmt=$db.prepare("DELETE from contact WHERE firstname=? and lastname=?")
	$db.transaction
	stmt.execute(firstname, lastname)
	$db.commit
end

#db_del_custom_monitoring(node_ip, node_type) ⇒ Object

remove all custom monitoring for a specific node



656
657
658
659
660
661
662
663
664
665
666
# File 'lib/node_db.rb', line 656

def db_del_custom_monitoring(node_ip, node_type)
stmt=$db.prepare("SELECT id, node_and_custom_monitor_id FROM node WHERE ip=? and nodetype=?")
 	stmt.execute(node_ip,node_type) do |rs|
		rs.each do |nodeid,nodesnmpmonid|
     			$db.transaction
					stmt2=$db.prepare("DELETE from node_and_custom_monitor WHERE node_id=? and id=?")
			 		stmt2.execute(nodeid,nodesnmpmonid)
					$db.commit
		end
	end
end

#db_del_groups(node_ip, node_type) ⇒ Object

remove all groups stuff for a specific node



755
756
757
# File 'lib/node_db.rb', line 755

def db_del_groups(node_ip, node_type)

end

#db_del_interfaces(node_ip, node_type) ⇒ Object

remove all interfaces stuff for a specific node



727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
# File 'lib/node_db.rb', line 727

def db_del_interfaces(node_ip, node_type)
	stmt=$db.prepare("SELECT id, node_and_interface_id FROM node WHERE ip=? and nodetype=?")
 	stmt.execute(node_ip,node_type) do |rs|
		rs.each do |nodeid,nodeinterfaceid|
			if nodeinterfaceid
				stmt=$db.prepare("SELECT distinct interface_id FROM node_and_interface WHERE node_id=? and id=?")
		 		stmt.execute(nodeid, nodeinterfaceid) do |rs|
					rs.each do |interfaceid|
						if interfaceid
							stmt2=$db.prepare("DELETE from interface WHERE id=?")
			      				$db.transaction
					 		stmt2.execute(interfaceid)
							$db.commit
						end
					end
					stmt3=$db.prepare("DELETE from node_and_interface WHERE node_id=? and id=?")
			      		$db.transaction
					stmt3.execute(nodeid,nodeinterfaceid)
					$db.commit										
				end
			end	
		end
	end
end

#db_del_jmx_monitoring(node_ip, node_type) ⇒ Object

remove all jmx monitoring stuff for a specific node



1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
# File 'lib/node_db.rb', line 1005

def db_del_jmx_monitoring(node_ip, node_type)
	stmt=$db.prepare("SELECT id, node_and_jmx_monitor_id FROM node WHERE ip=? and nodetype=?")
 	stmt.execute(node_ip,node_type) do |rs|
		rs.each do |nodeid,nodejmxid|
			if nodejmxid
				stmt=$db.prepare("SELECT jmx_monitor_id, jmx_attr_monitor_id FROM node_and_jmx_monitor WHERE node_id=? and id=?")
		 		stmt.execute(nodeid, nodejmxid) do |rs|
					rs.each do |jmxmonid, jmxattrmonid|
						if jmxmonid
							#we can pass here multiple time
							stmt=$db.prepare("DELETE from jmx_monitor WHERE id=?")
	      						$db.transaction
					 		stmt.execute(jmxmonid)
							$db.commit
						end
						if jmxattrmonid
							stmt=$db.prepare("DELETE from jmx_attr_monitor WHERE id=?")
	      						$db.transaction
					 		stmt.execute(jmxattrmonid)
							$db.commit
						end
					end
     					$db.transaction
					stmt2=$db.prepare("DELETE from node_and_jmx_monitor WHERE node_id=? and id=?")
			 		stmt2.execute(nodeid,nodejmxid)
					$db.commit
				end
			end	
		end
	end
end

remove all links stuff for a specific node



924
925
926
927
928
929
930
931
932
933
934
935
936
937
# File 'lib/node_db.rb', line 924

def db_del_links(node_ip=nil, node_type=nil)
	if !node_ip
		stmt=$db.prepare("DELETE from link")
		$db.transaction
		stmt.execute()
		$db.commit
	else
		nid=db_get_node_id(node_ip, node_type)
		stmt=$db.prepare("DELETE from link WHERE node1=? or node2=?")
		$db.transaction
		stmt.execute(nid,nid)
		$db.commit										
	end
end

#db_del_services(node_ip, node_type) ⇒ Object

remove all service monitoring for a specific node



638
639
640
641
642
643
644
645
646
647
648
649
650
651
# File 'lib/node_db.rb', line 638

def db_del_services(node_ip, node_type)
	stmt=$db.prepare("SELECT id, service_monitor_id FROM node WHERE ip=? and nodetype=?")
 	stmt.execute(node_ip,node_type) do |rs|
		rs.each do |nodeid,servicemid|
			#check if we already monitor service
			if servicemid
				stmt=$db.prepare("DELETE from service_monitor WHERE node_id=? and id=?")
				$db.transaction
		 		stmt.execute(nodeid, servicemid)
				$db.commit
			end	
		end
	end
end

#db_del_snmp_monitoring(node_ip, node_type) ⇒ Object

remove all snmp monitoring stuff for a specific node



991
992
993
# File 'lib/node_db.rb', line 991

def db_del_snmp_monitoring(node_ip, node_type)
	db_del_template_monitoring("snmp", node_ip, node_type)
end

#db_del_snmptrap_monitoring(node_ip, node_type) ⇒ Object

remove all snmp trap monitoring stuff for a specific node



1040
1041
1042
# File 'lib/node_db.rb', line 1040

def db_del_snmptrap_monitoring(node_ip, node_type)
	db_del_template_monitoring("snmptrap", node_ip, node_type)
end

#db_del_syslog_monitoring(node_ip, node_type) ⇒ Object

remove all syslog monitoring stuff for a specific node



1047
1048
1049
# File 'lib/node_db.rb', line 1047

def db_del_syslog_monitoring(node_ip, node_type)
	db_del_template_monitoring("syslog", node_ip, node_type)
end

#db_del_template_monitoring(templ, node_ip, node_type) ⇒ Object

remove all monitoring stuff based on a given monitoring template for a specific node



671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
# File 'lib/node_db.rb', line 671

def db_del_template_monitoring(templ, node_ip, node_type)
	stmt=$db.prepare("SELECT id, node_and_#{templ}_monitor_id FROM node WHERE ip=? and nodetype=?")
 	stmt.execute(node_ip,node_type) do |rs|
		rs.each do |nodeid,nodesnmpmonid|
			if nodesnmpmonid
				stmt=$db.prepare("SELECT distinct #{templ}_monitor_id FROM node_and_#{templ}_monitor WHERE node_id=? and id=?")
		 		stmt.execute(nodeid, nodesnmpmonid) do |rs|
					rs.each do |snmpmonid|
						if snmpmonid
							stmt=$db.prepare("DELETE from #{templ}_monitor WHERE id=?")
	      				$db.transaction
					 		stmt.execute(snmpmonid)
							$db.commit
						end
					end
     				$db.transaction
					stmt2=$db.prepare("DELETE from node_and_#{templ}_monitor WHERE node_id=? and id=?")
			 		stmt2.execute(nodeid,nodesnmpmonid)
					$db.commit
				end
			end	
		end
	end
end

#db_del_wmi_monitoring(node_ip, node_type) ⇒ Object

remove all wmi monitoring stuff for a specific node



998
999
1000
# File 'lib/node_db.rb', line 998

def db_del_wmi_monitoring(node_ip, node_type)
	db_del_template_monitoring("wmi", node_ip, node_type)
end

#db_delete_all_node_prpObject



1073
1074
1075
# File 'lib/node_db.rb', line 1073

def db_delete_all_node_prp()
	return $db.prepare("DELETE FROM node")
end

#db_delete_all_prp(table) ⇒ Object



1056
1057
1058
1059
1060
1061
1062
1063
# File 'lib/node_db.rb', line 1056

def db_delete_all_prp(table)
	begin
		return $db.prepare("DELETE FROM #{table}")
	rescue Exception => msg
		$log.info("Error when trying to delete table: #{msg}")
		return nil
	end
end

#db_delete_node(node_type, ip, mask) ⇒ Object

delete a node from the db and all the stuff around it



1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
# File 'lib/node_db.rb', line 1113

def db_delete_node(node_type, ip, mask)
	#sqlite does not support cascading delete
	begin
		db_del_services(ip, node_type)
		db_del_snmp_monitoring(ip, node_type)
		db_del_wmi_monitoring(ip, node_type)
		db_del_jmx_monitoring(ip, node_type)
		db_del_snmptrap_monitoring(ip, node_type)
		db_del_syslog_monitoring(ip, node_type)
		db_del_custom_monitoring(ip, node_type)
		db_del_links(ip, node_type)
		db_del_accounts(ip, node_type)
		db_del_interfaces(ip, node_type)
		db_del_groups(ip, node_type)
		db_del_alert_override(ip, node_type)

		$db.transaction
		stmt=$db.prepare("DELETE FROM node WHERE nodetype=? and ip=? and netmask=?")
		stmt.execute(node_type,ip,mask)
		$db.commit
	rescue Exception => msg
		$log.error("Error when trying to delete #{ip}/#{mask} from db #{msg.backtrace.join("\n")}")
	end
end

#db_get_accounts(ip, ntype) ⇒ Object



264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
# File 'lib/node_db.rb', line 264

def db_get_accounts(ip, ntype)
	haccount=Hash.new
	stmt=$db.prepare("SELECT id, node_and_account_id FROM node WHERE ip=? and nodetype=?")
	stmt.execute(ip, ntype) do |rs|
	      rs.each do |nodeid, naccountid|
		      if naccountid
			stmt2=$db.prepare("SELECT account_id FROM node_and_account WHERE node_id=? and id=?")
	   		stmt2.execute(nodeid, naccountid) do |rs|
	      			rs.each do |accountid|
					stmt3=$db.prepare("SELECT idname, login, password  FROM account WHERE id=?")
					stmt3.execute(accountid) do |rs|
						rs.each do |idn, lg, pass|
							#fill the hash
							haccount[idn]=[lg, Fog.decrypt(Base64.decode64(pass),GNMSKEY)]
						end
					end
				end
			
			end
		      end
	      end
	 end
	return haccount
end

#db_get_alert_override(node, node_type) ⇒ Object

get alert override



780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
# File 'lib/node_db.rb', line 780

def db_get_alert_override(node, node_type)
	nid=db_get_node_id(node.ip, node_type)
	stmt=$db.prepare("SELECT alert_override_detail_id, alert_type_by_level FROM alert_override WHERE node_id=?")
	stmt.execute(nid) do |rs|
			cpt=0
			rs.each do |aodid, atbl|				
				cpt+=1
				stmt2=$db.prepare("SELECT mail_state, mail_by_level_id, popup_state, beep_state, sound_file_path_by_level, syslog_state,sms_state, sms_num_by_level_id, im_state,im_dest_by_level_id, script_state, script_name_by_level, irc_state FROM alert_override_detail WHERE id=?")
				stmt2.execute(aodid) do |rs|
					rs.each do |mail_state, mail_by_level_id, popup_state, beep_state, sound_file_path_by_level, syslog_state,sms_state, sms_num_by_level_id, im_state,im_dest_by_level_id, script_state, script_name_by_level, irc_state|
						node.alert_type_by_level[atbl][0]=mail_state.to_b
						node.mail_by_level[atbl]=db_get_alert_override_contact_array(mail_by_level_id)
						node.alert_type_by_level[atbl][1]=popup_state.to_b
						node.alert_type_by_level[atbl][2]=beep_state.to_b
						node.sound_file_path_by_level[atbl]=sound_file_path_by_level
						node.alert_type_by_level[atbl][3]=syslog_state.to_b
						node.alert_type_by_level[atbl][4]=sms_state.to_b
						node.sms_num_by_level[atbl]=db_get_alert_override_contact_array(sms_num_by_level_id)
						node.alert_type_by_level[atbl][5]=im_state.to_b
						node.im_dest_by_level[atbl]=db_get_alert_override_contact_array(im_dest_by_level_id)
						node.alert_type_by_level[atbl][6]=script_state.to_b
						node.script_name_by_level[atbl]=script_name_by_level												
						node.alert_type_by_level[atbl][7]=irc_state.to_b
					end
				end
			end	
			
			if cpt > 0
				node.set_inherit_conf(false)
			end
	end
end

#db_get_alert_override_contact_array(id) ⇒ Object

return an array of Contact_selected_info for a given id



763
764
765
766
767
768
769
770
771
772
773
774
775
# File 'lib/node_db.rb', line 763

def db_get_alert_override_contact_array(id)
	contactt=Array.new
	stmt=$db.prepare("SELECT contact_id FROM alert_override_contact WHERE id=?")
	stmt.execute(id) do |rs|
		rs.each do |cid|
			if cid
				(firstname, lastname)=db_get_contact_names(cid)
				contactt.push(Contact_selected_info.new(firstname,lastname))
			end
		end
	end
	return contactt
end

#db_get_contact_id(firstname, lastname) ⇒ Object

return contact id



1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
# File 'lib/node_db.rb', line 1389

def db_get_contact_id(firstname, lastname)
	stmt=$db.prepare("SELECT id FROM contact WHERE firstname=? and lastname=?")
	stmt.execute(firstname, lastname) do |rs|
		rs.each do |cid|
			if cid
				return cid
			end
		end
	end	
end

#db_get_contact_names(id) ⇒ Object

return array of firstname and lastname for a given contact



1403
1404
1405
1406
1407
1408
1409
1410
# File 'lib/node_db.rb', line 1403

def db_get_contact_names(id)
	stmt=$db.prepare("SELECT firstname, lastname FROM contact WHERE id=?")
	stmt.execute(id) do |rs|
		rs.each do |firstname, lastname|
				return [firstname, lastname]
		end
	end	
end

#db_get_custom_monitor_id(cm_name_id) ⇒ Object



1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
# File 'lib/node_db.rb', line 1084

def db_get_custom_monitor_id(cm_name_id)
	stmt=$db.prepare("SELECT id FROM custom_monitor WHERE name=?")
 	stmt.execute(cm_name_id) do |rs|
		rs.each do |field,type|
			if !field
				return 0
			end
			return field.to_i
		end
	end
	return 0
end

#db_get_interfaces(nodeid, nodeandinterface_id) ⇒ Object



289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
# File 'lib/node_db.rb', line 289

def db_get_interfaces(nodeid, nodeandinterface_id)
	haccount=Hash.new
	stmt2=$db.prepare("SELECT interface_id FROM node_and_interface WHERE node_id=? and id=?")
	stmt2.execute(nodeid, nodeandinterface_id) do |rs|
	  rs.each do |interfaceid|
		stmt3=$db.prepare("SELECT name, link_status, speed FROM interface WHERE id=?")
		stmt3.execute(interfaceid) do |rs|
			rs.each do |n, lstatus, sp|
			#fill the hash
			haccount[n]=Interface.new(n, lstatus, sp)
			end
		end
	  end
	end
	return haccount
end

#db_get_ip(nid) ⇒ Object

return the ip corresponding to a given node id



1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
# File 'lib/node_db.rb', line 1162

def db_get_ip(nid)
	if nid
		stmt=$db.prepare("SELECT ip FROM node WHERE id=?")
 		stmt.execute(nid) do |rs|
			rs.each do |field,type|
				if !field
					return nil
				end
				return field
			end
		end
	end
	return nil		
end

#db_get_ip_type(nid) ⇒ Object

return an array of ip and type corresponding to a given node id



1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
# File 'lib/node_db.rb', line 1180

def db_get_ip_type(nid)
	if nid
		stmt=$db.prepare("SELECT ip, nodetype FROM node WHERE id=?")
 		stmt.execute(nid) do |rs|
			rs.each do |ip,type|
				return [ip, type]
			end
		end
	end
	return nil		
end

#db_get_jmx_monitoring(ip, type) ⇒ Object



1213
1214
1215
1216
1217
1218
1219
1220
# File 'lib/node_db.rb', line 1213

def db_get_jmx_monitoring(ip, type)
	stmt=$db.prepare("SELECT id, node_and_jmx_monitor_id FROM node WHERE nodetype=? and ip=?")
	stmt.execute(type, ip) do |rs|
		rs.each do |id, jmxid|
			db_get_jmx_monitoring_ids(ip, id, jmxid)
		end
	end
end

#db_get_jmx_monitoring_ids(ip, id, node_and_jmx_monitor_id) ⇒ Object



1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
# File 'lib/node_db.rb', line 1222

def db_get_jmx_monitoring_ids(ip, id, node_and_jmx_monitor_id)
	stmt=$db.prepare("SELECT distinct jmx_monitor.id, jmx_state, jmx_ref_name, jmx_protocol, jmx_port, jmx_auth FROM node_and_jmx_monitor, jmx_monitor WHERE node_id=? and node_and_jmx_monitor.id=? and jmx_monitor_id=jmx_monitor.id")
	stmt.execute(id, node_and_jmx_monitor_id) do |rs|
	rs.each do |jmx_id, state, jmxref, proto, port, auth|
		attribuesh=Hash.new
		stmt=$db.prepare("SELECT name, oper, value, jmxsev FROM node_and_jmx_monitor, jmx_attr_monitor WHERE node_id=? and node_and_jmx_monitor.id=? and jmx_attr_monitor_id=jmx_attr_monitor.id and node_and_jmx_monitor.jmx_monitor_id=?")
		stmt.execute(id, node_and_jmx_monitor_id, jmx_id) do |rs|
		rs.each do |name, oper, value, jmxsev|
				attribuesh[name]=JmxAttributeMonitoring.new(name, oper.to_i(), value.to_i(), jmxsev.to_i())
			end
		end
		$host[ip].add_jmx_monitoring(state.to_i(), jmxref, proto, port.to_i(), auth, attribuesh.dup)
		end
	end
end

call Link class and fill directly the $links



942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
# File 'lib/node_db.rb', line 942

def db_get_links()
	stmt=$db.prepare("SELECT link_state, name, speed, node1, node2 FROM link")
 	stmt.execute() do |rs|
		rs.each do |link_state, name, speed, node1, node2|
			ip1, nodetype1 = db_get_ip_type(node1)
			ip2, nodetype2 = db_get_ip_type(node2)
			if nodetype1 == HOSTNODE
				node1=$host[ip1]
			else
				node1=$network[ip1]
			end
			if nodetype2 == HOSTNODE
				node2=$host[ip2]
			else
				node2=$network[ip2]
			end
			Link.new(node1, node2)
		end
	end
end

#db_get_network_id(map) ⇒ Object



1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
# File 'lib/node_db.rb', line 1097

def db_get_network_id(map)
	stmt=$db.prepare("SELECT id FROM node WHERE nodetype=? and ip=?")
 	stmt.execute(NETWORKNODE, map) do |rs|
		rs.each do |field,type|
			if !field
				return 0
			end
			return field.to_i
		end
	end
	return 0
end

#db_get_node_account_id(nid) ⇒ Object



212
213
214
215
216
217
218
219
220
221
222
223
224
# File 'lib/node_db.rb', line 212

def (nid)

	stmt=$db.prepare("SELECT node_and_account_id FROM node WHERE id=?")
 	stmt.execute(nid) do |rs|
		rs.each do |field,type|
			if !field
				return 0
			end
			return field
		end
	end
	return 0
end

#db_get_node_custom_monitor_id(nid) ⇒ Object



260
261
262
# File 'lib/node_db.rb', line 260

def db_get_node_custom_monitor_id(nid)
	return db_get_node_template_monitor_id("custom", nid)
end

#db_get_node_id(ip, ntype) ⇒ Object



184
185
186
187
188
189
190
191
192
193
194
195
196
# File 'lib/node_db.rb', line 184

def db_get_node_id(ip, ntype)

	stmt=$db.prepare("SELECT id FROM node WHERE ip=? and nodetype=?")
 	stmt.execute(ip, ntype) do |rs|
		rs.each do |field,type|
			if !field
			   return 0
			end
			   return field
		end
	end
	return 0
end

#db_get_node_interface_id(nid) ⇒ Object



226
227
228
229
230
231
232
233
234
235
236
237
238
# File 'lib/node_db.rb', line 226

def db_get_node_interface_id(nid)

	stmt=$db.prepare("SELECT node_and_interface_id FROM node WHERE id=?")
 	stmt.execute(nid) do |rs|
		rs.each do |field,type|
			if !field
				return 0
			end
			return field
		end
	end
	return 0
end

#db_get_node_jmx_monitor_id(nid) ⇒ Object



248
249
250
# File 'lib/node_db.rb', line 248

def db_get_node_jmx_monitor_id(nid)
	return db_get_node_template_monitor_id("jmx", nid)
end

#db_get_node_snmp_monitor_id(nid) ⇒ Object



240
241
242
# File 'lib/node_db.rb', line 240

def db_get_node_snmp_monitor_id(nid)
	return db_get_node_template_monitor_id("snmp", nid)
end

#db_get_node_snmptrap_monitor_id(nid) ⇒ Object



252
253
254
# File 'lib/node_db.rb', line 252

def db_get_node_snmptrap_monitor_id(nid)
	return db_get_node_template_monitor_id("snmptrap", nid)
end

#db_get_node_syslog_monitor_id(nid) ⇒ Object



256
257
258
# File 'lib/node_db.rb', line 256

def db_get_node_syslog_monitor_id(nid)
	return db_get_node_template_monitor_id("syslog", nid)
end

#db_get_node_template_monitor_id(templ, nid) ⇒ Object



198
199
200
201
202
203
204
205
206
207
208
209
210
# File 'lib/node_db.rb', line 198

def db_get_node_template_monitor_id(templ, nid)

	stmt=$db.prepare("SELECT node_and_#{templ}_monitor_id FROM node WHERE id=?")
 	stmt.execute(nid) do |rs|
		rs.each do |field,type|
			if !field
				return 0
			end
			return field
		end
	end
	return 0
end

#db_get_node_wmi_monitor_id(nid) ⇒ Object



244
245
246
# File 'lib/node_db.rb', line 244

def db_get_node_wmi_monitor_id(nid)
	return db_get_node_template_monitor_id("wmi", nid)
end

#db_get_service_id(protocol, number) ⇒ Object

return the service id associated to the protocol/number



170
171
172
173
174
175
176
177
178
179
180
181
182
# File 'lib/node_db.rb', line 170

def db_get_service_id(protocol, number)

	stmt=$db.prepare("SELECT id FROM service WHERE protocol=? and port=?")
 	stmt.execute(protocol,number) do |rs|
		rs.each do |field,type|
			if !field
				return 0
			end
			return field
		end
	end
	return 0
end

#db_get_services(nodeid, service_monitor_id) ⇒ Object

return a hash of all services for a given node id and service monitor id



1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
# File 'lib/node_db.rb', line 1195

def db_get_services(nodeid, service_monitor_id)
		if !service_monitor_id		
			return nil
		end
		services=Hash.new
		stmt=$db.prepare("SELECT protocol, port, name, monitor, service_sev FROM service, service_monitor WHERE service_monitor.node_id=? and service_monitor.id=? and service_monitor.service_id=service.id")
		stmt.execute(nodeid, service_monitor_id) do |rs|
			rs.each do |proto, port, name, monitor, sev|
					services["#{proto}/#{port}"]=Service.new(proto, port.to_i, name, monitor, sev.to_i)
			end
		end
		if services.size() == 0
			return nil
		else
			return services
		end
end

#db_insert_custom_monitor(cm_name_id) ⇒ Object



1077
1078
1079
1080
1081
1082
# File 'lib/node_db.rb', line 1077

def db_insert_custom_monitor(cm_name_id)
	stmt=$db.prepare("INSERT INTO custom_monitor VALUES (NULL,?)")
	$db.transaction
 	stmt.execute(cm_name_id)
	$db.commit
end

#db_insert_node_prp(uuid, nodetype, ip, mask, ipv6, mask6, mac, map, status, avail_sev, snmp_sev, custom_sev, trap_sev, serv_sev, wmi_sev, syslog_sev, jmx_sev, x, y, icon, description, snmp_version, snmp_port, snmp_timeout, snmp_retry, type, os, name, dns_name, dns_domain, netbios_name, netbios_domain, nodesize, bg_type, bg_data) ⇒ Object



1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
# File 'lib/node_db.rb', line 1138

def db_insert_node_prp(uuid,nodetype,ip,mask,ipv6,mask6,mac,map,status,avail_sev,snmp_sev,custom_sev,trap_sev, serv_sev, wmi_sev, syslog_sev, jmx_sev, x,y,icon,description,snmp_version,snmp_port,snmp_timeout,snmp_retry,type,os,name,dns_name,dns_domain,netbios_name,netbios_domain,nodesize,bg_type,bg_data)
	  if defined?($db) && ($db !=nil)
		stmt=$db.prepare("SELECT count(id) FROM node WHERE nodetype=? and ip=? and netmask=?")
	 	stmt.execute(nodetype,ip,mask) do |rs|
			rs.each do |field,vtype|
				if field.to_i==0
				  map_id=db_get_network_id(map)
				  begin
					  $db.transaction
					  stmt=$db.prepare("INSERT INTO node VALUES (NULL,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)")
					  stmt.execute(uuid,nodetype,ip,mask,ipv6,mask6,mac,map_id,status,avail_sev,snmp_sev,custom_sev,trap_sev, serv_sev, wmi_sev, syslog_sev, jmx_sev,x,y,icon,description,snmp_version,snmp_port,snmp_timeout,snmp_retry,type,os,name,dns_name,dns_domain,netbios_name,netbios_domain,nodesize,bg_type,bg_data)
					  $db.commit
				  rescue
				  	$log.error("Error when adding a new node in database")
				  end
				end
			end
		end
	  end
end

#db_insert_ref_prp(table) ⇒ Object



1069
1070
1071
# File 'lib/node_db.rb', line 1069

def db_insert_ref_prp(table)
	return $db.prepare("INSERT INTO #{table} VALUES (?, ?, ?)")
end

#db_insert_ref_prp4(table) ⇒ Object



1065
1066
1067
# File 'lib/node_db.rb', line 1065

def db_insert_ref_prp4(table)
	return $db.prepare("INSERT INTO #{table} VALUES (?, ?, ?, ?)")
end

#db_read(fic = SQLITE_DB) ⇒ Object

read and init component hash



1453
1454
1455
1456
1457
1458
1459
1460
1461
# File 'lib/node_db.rb', line 1453

def db_read(fic=SQLITE_DB)
	open_db(fic)
	db_check_version_schema()
	db_read_refs()
  db_set_custom_monitor()
	db_read_contact()	
	db_read_node()
	db_get_links()
end

#db_read_contactObject

read contacts information and fill hash



1376
1377
1378
1379
1380
1381
1382
1383
1384
# File 'lib/node_db.rb', line 1376

def db_read_contact()
	stmt=$db.prepare("SELECT firstname, lastname, email, phone, mobile, pager, im, title, organization, location, note FROM contact")
 	stmt.execute() do |rs|
		rs.each do |firstname, lastname, email, phone, mobile, pager, im, title, organization, location, note|
			$contact["#{firstname}|#{lastname}"]=Contact.new(firstname, lastname, email, phone, mobile, pager, im, title, organization, location, note)
		end
	end
	return 0
end

#db_read_nodeObject



1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
# File 'lib/node_db.rb', line 1238

def db_read_node()

	#first read network node details
	#here we want recursive network id, map id is increasingm and 0 is the root map
	stmt=$db.prepare("SELECT * FROM node WHERE nodetype='n' ORDER BY map")
	networkinmap=Hash.new
	stmt.execute() do |rs|
		rs.each do |id, uuid, nodetype, ip, mask, ipv6, mask6, mac, map, status, avail_sev, snmp_sev,custom_sev,trap_sev, serv_sev, wmi_sev, syslog_sev, jmx_sev, service_monitor_id,node_and_snmp_monitor_id,node_and_wmi_monitor_id, node_and_jmx_monitor_id, node_and_snmptrap_monitor_id,node_and_syslog_monitor_id, node_and_custom_monitor_id, ,node_and_group_id, node_and_interface_id, x,y,icon,description, snmp_version,snmp_port, snmp_timeout, snmp_retry,type,os,name,dns_name,dns_domain,netbios_name,netbios_domain,node_size,map_bg_type,map_bg_data|
		
		#read service
		services=db_get_services(id, service_monitor_id)
		map_ip=db_get_ip(map)
		nnode=Network.new(ip, mask.to_i, ipv6, mask6.to_i, map_ip, services, status.to_i, x.to_i, y.to_i, icon, description, type, os, name, dns_domain, netbios_domain, uuid)
		nnode.snmp_version=snmp_version
		nnode.snmp_port=snmp_port
		nnode.snmp_timeout=snmp_timeout
		nnode.snmp_retry=snmp_retry
		
		if node_size.to_i() == 0
			nnode.node_size=NodeView::NODE_SIZE
		else
			nnode.node_size=node_size.to_i()
		end
		
		nnode.map_bg_type=map_bg_type
		if map_bg_type == "color"
			#rgb is store as a text space char separated
			nnode.map_bg_data=map_bg_data.split
		else
			nnode.map_bg_data=map_bg_data
		end
		nnode.(db_get_accounts(ip, nodetype))
		
		#load alert override
		db_get_alert_override(nnode, NETWORKNODE)
		
		nnode.reload
		networkinmap[ip]=map_ip
		$network[ip]=nnode
		end
	end
	networkinmap.each_pair do |network_ip, map|
		$network[map].add_network($network[network_ip]) unless map == nil
	end	
	
	#then read the other nodes
	stmt=$db.prepare("SELECT * FROM node WHERE nodetype!='n' ORDER BY ip")
		stmt.execute() do |rs|
			rs.each do |id, uuid, nodetype, ip, mask, ipv6, mask6, mac, map, status, avail_sev, snmp_sev,custom_sev,trap_sev, serv_sev, wmi_sev, syslog_sev, jmx_sev, service_monitor_id,node_and_snmp_monitor_id,node_and_wmi_monitor_id, node_and_jmx_monitor_id, node_and_snmptrap_monitor_id,node_and_syslog_monitor_id, node_and_custom_monitor_id,,node_and_group_id, node_and_interface_id, x,y,icon,description, snmp_version,snmp_port, snmp_timeout, snmp_retry,type,os,name,dns_name,dns_domain,netbios_name,netbios_domain,node_size,map_bg_type,map_bg_data|
			
			#read service
			services=db_get_services(id, service_monitor_id)
			map_ip=db_get_ip(map)
			nnode=Host.new(ip, mask.to_i, ipv6, mask6.to_i, map_ip, mac, dns_name, netbios_name, services, status.to_i, x.to_i, y.to_i, icon, description, type, os, uuid)
			nnode.set_severities(avail_sev.to_i, snmp_sev.to_i, custom_sev.to_i, trap_sev.to_i,serv_sev.to_i, wmi_sev.to_i, syslog_sev.to_i, jmx_sev.to_i)
			nnode.(db_get_accounts(ip, nodetype))
			nnode.set_all_interface(db_get_interfaces(id, node_and_interface_id))
			nnode.name = name
			nnode.reload
			
			$host[ip]=nnode

			if node_and_snmp_monitor_id
				stmt=$db.prepare("SELECT snmp_state, oid_ref_name, oper, threshold, oidsev FROM node_and_snmp_monitor, snmp_monitor WHERE node_id=? and node_and_snmp_monitor.id=? and snmp_monitor_id=snmp_monitor.id")
				stmt.execute(id, node_and_snmp_monitor_id) do |rs|
					rs.each do |state, oidref, oper, threshold, sev|
						$host[ip].add_snmp_monitoring(state.to_i(), oidref, oper.to_i(), threshold, sev.to_i(),"init")
					end
				end
			end
			
			if node_and_wmi_monitor_id
				stmt=$db.prepare("SELECT wmi_state, wmi_ref_name, oper, value, wmisev FROM node_and_wmi_monitor, wmi_monitor WHERE node_id=? and node_and_wmi_monitor.id=? and wmi_monitor_id=wmi_monitor.id")
				stmt.execute(id, node_and_wmi_monitor_id) do |rs|
					rs.each do |state, wmiref, oper, val, sev|
						$host[ip].add_wmi_monitoring(state.to_i(), wmiref, oper.to_i(), val, sev.to_i(), "init")
					end
				end
			end

			if node_and_jmx_monitor_id
				db_get_jmx_monitoring_ids(ip, id, node_and_jmx_monitor_id)
			end			

			if node_and_snmptrap_monitor_id
				stmt=$db.prepare("SELECT snmptrap_state, snmptrap_ref, snmptrap_sev FROM node_and_snmptrap_monitor, snmptrap_monitor WHERE node_id=? and node_and_snmptrap_monitor.id=? and snmptrap_monitor_id=snmptrap_monitor.id")
				stmt.execute(id, node_and_snmptrap_monitor_id) do |rs|
					rs.each do |state, ref, sev|
						$host[ip].add_snmptrap_monitoring(state.to_i(), ref, sev.to_i(),"init")
					end
				end
			end
			
			if node_and_syslog_monitor_id
				stmt=$db.prepare("SELECT syslog_state, syslog_ref, syslog_sev FROM node_and_syslog_monitor, syslog_monitor WHERE node_id=? and node_and_syslog_monitor.id=? and syslog_monitor_id=syslog_monitor.id")
				stmt.execute(id, node_and_syslog_monitor_id) do |rs|
					rs.each do |state, ref, sev|
						$host[ip].add_syslog_monitoring(state.to_i(), ref, sev.to_i(),"init")
					end
				end
			end
			
      if node_and_custom_monitor_id
				stmt=$db.prepare("SELECT custom_state, custom_name, custom_param, custom_sev FROM node_and_custom_monitor, custom_monitor WHERE node_id=? and node_and_custom_monitor.id=? and custom_monitor_id=custom_monitor.id")
				stmt.execute(id, node_and_custom_monitor_id) do |rs|
					rs.each do |state, name, param, sev|
						$host[ip].add_custom_monitoring(state.to_i(), name, param, sev.to_i(), "init")
					end
				end
			end      
      
			$network[map_ip].add_host(nnode)
			$network[map_ip].update_status()			

			end
	end
end

#db_read_refsObject



1442
1443
1444
1445
1446
1447
1448
# File 'lib/node_db.rb', line 1442

def db_read_refs()
   OIDRef::read_db_oidref()
   WMIRef::read_db_wmiref()
   JMXRef::read_db_jmxref()
   SyslogRef::read_db_syslogref()
   SnmpTrapRef::read_db_snmptrapref()
end

#db_select_all_prp(table) ⇒ Object



1052
1053
1054
# File 'lib/node_db.rb', line 1052

def db_select_all_prp(table)
	return $db.prepare("SELECT * FROM #{table}")
end

#db_set_account(nodeid, idname, login, passwd) ⇒ Object

set an account to a specific node



595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
# File 'lib/node_db.rb', line 595

def (nodeid, idname, , passwd)
	nodeaccountid=(nodeid)
	password=Base64.encode64(Fog.new(passwd,GNMSKEY))
	if nodeaccountid == 0
			   stmt=$db.prepare("UPDATE node SET node_and_account_id=(SELECT IFNULL(MAX(id),0) FROM node_and_account)+1 WHERE id=?")
				$db.transaction
				stmt.execute(nodeid)
				$db.commit
				nodeaccountid=(nodeid)
	end

	if nodeaccountid != 0
		stmt2=$db.prepare("SELECT account_id FROM node_and_account WHERE node_id=? and id=?")
		stmt2.execute(nodeid, nodeaccountid) do |rs|
			rs.each do |accountid|
				$db.transaction
				stmt3=$db.prepare("UPDATE account SET login=?,password=? WHERE id=? and idname=?")
				stmt3.execute(, password, accountid, idname)
				$db.commit
				return
			end
		end			
	else
		$log.error("db_set_account: something goes wrong trying to find the account id")
		return
	end
end

#db_set_alert_override(node, node_type) ⇒ Object

set alert override for a specific node



816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
# File 'lib/node_db.rb', line 816

def db_set_alert_override(node, node_type)
	nid=db_get_node_id(node.ip, node_type)
	$LEVEL.each {|lvl|
		mail_id=nil
		sms_id=nil
		im_id=nil
		stmt=$db.prepare("SELECT IFNULL(MAX(id),0)+1 FROM alert_override_contact")
		stmt2=$db.prepare("INSERT INTO alert_override_contact VALUES (?,?)")
		stmt.execute() do |rs|
			rs.each do |maxid,type|
				id=maxid.to_i
				
				if node.mail_by_level[lvl]
				node.mail_by_level[lvl].each {|contact|
						cid=db_get_contact_id(contact.firstname, contact.lastname)
						if cid
							stmt2.execute(id, cid)
						end
					}
					mail_id=id
					id+=1
				else
					maid_id=nil
				end
				if node.sms_num_by_level[lvl]
				node.sms_num_by_level[lvl].each {|contact|
						cid=db_get_contact_id(contact.firstname, contact.lastname)
						if cid
							stmt2.execute(id, cid)
						end
					}
					sms_id=id
					id+=1
				else
					sms_id=nil
				end
				if node.im_dest_by_level[lvl]
				node.im_dest_by_level[lvl].each {|contact|
						cid=db_get_contact_id(contact.firstname, contact.lastname)
						if cid
							stmt2.execute(id, cid)
						end
					}
					im_id=id
					id+=1
				else
					im_id=nil
				end
			end
		end
	
		stmt=$db.prepare("INSERT INTO alert_override_detail VALUES (NULL, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)")
		$db.transaction
		stmt.execute(node.alert_type_by_level[lvl][0], mail_id, node.alert_type_by_level[lvl][1], node.alert_type_by_level[lvl][2],node.sound_file_path_by_level[lvl],node.alert_type_by_level[lvl][3],node.alert_type_by_level[lvl][4],sms_id,node.alert_type_by_level[lvl][5],im_id,node.alert_type_by_level[lvl][6],node.script_name_by_level[lvl])
		$db.commit
		stmt=$db.prepare("SELECT MAX(id) FROM alert_override_detail")
		stmt.execute() do |rs|
			rs.each do |aodid|
				if aodid
					stmt2=$db.prepare("INSERT INTO alert_override VALUES (NULL,?,?,?)")
					$db.transaction
					stmt2.execute(nid, aodid, lvl)
					$db.commit
				end
			end
		end
	}

end

#db_set_background(nodeid, bg_type, bg_data) ⇒ Object

set background conf for a specific nodeid



132
133
134
135
136
137
# File 'lib/node_db.rb', line 132

def db_set_background(nodeid, bg_type, bg_data)
	$db.transaction
	stmt=$db.prepare("UPDATE node SET map_bg_type=?, map_bg_data=? WHERE id=?")
	stmt.execute(bg_type, "#{bg_data}", nodeid)
	$db.commit
end

#db_set_custom_monitorObject

at db creation, populate the custom_monitor table with plugins found



310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
# File 'lib/node_db.rb', line 310

def db_set_custom_monitor()
  local_custom_monitor = []
  begin
  stmt1=$db.prepare("SELECT custom_name FROM custom_monitor")
	stmt1.execute() do |rs|
    rs.each do |cm_name|
      local_custom_monitor.push cm_name.to_s
    end
  end
  rescue Exception => msg
    $log.error("db_set_custom_monitor: #{msg}")
    return
  end
  if $custom_monitor
    stmt2=$db.prepare("INSERT INTO custom_monitor VALUES (NULL, ?)")
    $custom_monitor.each do |cm_name|
      #check if cm_name is not in the db
      if local_custom_monitor.index(cm_name).nil?
          $db.transaction
		stmt2.execute(cm_name)
          $db.commit
      end
    end
  end
end

#db_set_description(nodeid, desc) ⇒ Object

set description for a specific nodeid



70
71
72
73
74
75
# File 'lib/node_db.rb', line 70

def db_set_description(nodeid, desc)
	$db.transaction
	stmt=$db.prepare("UPDATE node SET description=? WHERE id=?")
	stmt.execute(desc, nodeid)
	$db.commit
end

#db_set_interfaces(ip, interfaces) ⇒ Object

set interfaces to a specific node



626
627
628
629
630
631
632
633
# File 'lib/node_db.rb', line 626

def db_set_interfaces(ip, interfaces)
        #removing entries from the db
	db_del_interfaces(ip, HOSTNODE)
	#saving interfaces in db
	interfaces.each_value {|intf|
	   db_add_interface(ip, HOSTNODE, intf.name, intf.link_status, intf.speed, intf.type)
	}
end

save link for a given node, this method save the $links array to db



966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
# File 'lib/node_db.rb', line 966

def db_set_links()
	$links.each {|link|
		node_ip1=link.node1.ip
		node_ip2=link.node2.ip
		node_type1=HOSTNODE
		if link.node1.class == Network
			node_type1=NETWORKNODE
		end
		node_type2=HOSTNODE
		if link.node2.class == Network
			node_type2=NETWORKNODE
		end	
		nid1=db_get_node_id(node_ip1, node_type1)
		nid2=db_get_node_id(node_ip2, node_type2)

      		stmt=$db.prepare("INSERT INTO link VALUES (?, ?, ?, ?, ?, ?)")
		$db.transaction
		stmt.execute(nil, 1, "", 0, nid1, nid2)
		$db.commit
	}
end

#db_set_mac(nodeid, mac) ⇒ Object

set mac addr for a specific nodeid



48
49
50
51
52
53
# File 'lib/node_db.rb', line 48

def db_set_mac(nodeid, mac)
	$db.transaction
	stmt=$db.prepare("UPDATE node SET mac=? WHERE id=?")
	stmt.execute(mac, nodeid)
	$db.commit
end

#db_set_map(nodeid, map_ip) ⇒ Object

set map for a specific nodeid



142
143
144
145
146
147
148
149
150
151
152
153
154
155
# File 'lib/node_db.rb', line 142

def db_set_map(nodeid, map_ip)
	#test if we are trying to set map for the root network
	if map_ip
		mapnodeid=db_get_node_id(map_ip,NETWORKNODE)
		if mapnodeid != 0
			$db.transaction
			stmt=$db.prepare("UPDATE node SET map=? WHERE id=?")
			stmt.execute(mapnodeid, nodeid)
			$db.commit
		else
			$log.error("db_set_map: can't find network map #{map_ip}")		
		end
	end
end

#db_set_mask(nodeid, mask) ⇒ Object

set mask as integer value for a specific nodeid



58
59
60
61
62
63
64
65
# File 'lib/node_db.rb', line 58

def db_set_mask(nodeid, mask)
	if isInteger(mask)
		$db.transaction
		stmt=$db.prepare("UPDATE node SET netmask=? WHERE id=?")
		stmt.execute(mask, nodeid)
		$db.commit
	end
end

#db_set_name(nodeid, name, dnsn, dnsd, netbiosn, netbiosd) ⇒ Object

set names for a specific nodeid depending of its type



160
161
162
163
164
165
# File 'lib/node_db.rb', line 160

def db_set_name(nodeid, name, dnsn, dnsd, netbiosn, netbiosd)
	$db.transaction
	stmt=$db.prepare("UPDATE node SET name=?, dns_name=?, dns_domain=?, netbios_name=?, netbios_domain=? WHERE id=?")
	stmt.execute(name, dnsn, dnsd, netbiosn, netbiosd, nodeid)
	$db.commit
end

#db_set_node_position(nodeid, x, y) ⇒ Object

set property x and y for a specific nodeid



100
101
102
103
104
105
# File 'lib/node_db.rb', line 100

def db_set_node_position(nodeid, x, y)
	$db.transaction
	stmt=$db.prepare("UPDATE node SET x=?, y=? WHERE id=?")
	stmt.execute(x, y, nodeid)
	$db.commit
end

#db_set_node_size(nodeid, node_size) ⇒ Object

set node size for a specific nodeid



120
121
122
123
124
125
126
127
# File 'lib/node_db.rb', line 120

def db_set_node_size(nodeid, node_size)
	if isInteger(node_size)
		$db.transaction
		stmt=$db.prepare("UPDATE node SET node_size=? WHERE id=?")
		stmt.execute(node_size, nodeid)
		$db.commit
	end
end

#db_set_node_type_and_os(nodeid, type, os) ⇒ Object

set property type and os for a specific nodeid



90
91
92
93
94
95
# File 'lib/node_db.rb', line 90

def db_set_node_type_and_os(nodeid, type, os)
	$db.transaction
	stmt=$db.prepare("UPDATE node SET type=?, os=? WHERE id=?")
	stmt.execute(type, os, nodeid)
	$db.commit
end

#db_set_severity(nodeid, st, avail, snmp, cstom, trap, serv, wmi, syslog, jmx) ⇒ Object

set severities for a specific nodeid



80
81
82
83
84
85
# File 'lib/node_db.rb', line 80

def db_set_severity(nodeid, st, avail, snmp, cstom, trap, serv, wmi, syslog, jmx)
	$db.transaction
	stmt=$db.prepare("UPDATE node SET status=?, avail_sev=?, snmp_sev=?, custom_sev=?, trap_sev=?, service_sev=?, wmi_sev=?, syslog_sev=?, jmx_sev=? WHERE id=?")
	stmt.execute(st, avail, snmp, cstom, trap, serv, wmi, syslog, jmx, nodeid)
	$db.commit
end

#db_set_snmp_parameter(nodeid, snmp_version, snmp_port, snmp_timeout, snmp_retry) ⇒ Object

set snmp properties for a specific nodeid



110
111
112
113
114
115
# File 'lib/node_db.rb', line 110

def db_set_snmp_parameter(nodeid, snmp_version, snmp_port, snmp_timeout, snmp_retry)
	$db.transaction
	stmt=$db.prepare("UPDATE node SET snmp_version=?, snmp_port=?, snmp_timeout=?, snmp_retry=? WHERE id=?")
	stmt.execute(snmp_version, snmp_port, snmp_timeout, snmp_retry, nodeid)
	$db.commit
end

#db_write_contact(firstname, lastname, email, phone, mobile, pager, im, title, organization, location, note) ⇒ Object

write contacts information



1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
# File 'lib/node_db.rb', line 1415

def db_write_contact(firstname, lastname, email, phone, mobile, pager, im, title, organization, location, note)
	cid=db_get_contact_id(firstname, lastname)
	if cid
		stmt2=$db.prepare("UPDATE contact SET firstname=?, lastname=?, email=?, phone=?, mobile=?, pager=?, im=?, title=?, organization=?, location=?, note=? WHERE id=?")
		$db.transaction
		stmt2.execute(firstname, lastname, email, phone, mobile, pager, im, title, organization, location, note, cid)
		$db.commit
	else
		stmt2=$db.prepare("INSERT INTO contact VALUES ((SELECT IFNULL(MAX(id),0) FROM contact)+1, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)")
		$db.transaction
		stmt2.execute(firstname, lastname, email, phone, mobile, pager, im, title, organization, location, note)
		$db.commit
	end
end

#del_host(ip) ⇒ Object

del host from a network



436
437
438
439
440
441
442
# File 'lib/main.rb', line 436

def del_host(ip)
  #we first update network list
  $network[$host[ip].map].del_host(ip)
  $network[$host[ip].map].update_status()
  $host.delete ip
  $event_win.update_statusbar()
end

#del_monitoring_thread(str) ⇒ Object

remove thread from thread group



267
268
269
270
271
272
273
# File 'lib/main.rb', line 267

def del_monitoring_thread(str)
  if $thread_list[str] != nil
    $log.debug("Removing thread #{str}")
    ThreadGroup.new.add($thread_list[str])
    $thread_list.delete(str)
  end
end

#del_network(ip) ⇒ Object

delete a network need: ip



474
475
476
477
478
479
480
481
482
483
484
485
486
487
# File 'lib/main.rb', line 474

def del_network(ip)
  if ip != ROOTMAPADDR
    $network[ip].get_node().each_key {|id|
      $host[id].delete() unless $host[id] == nil
    }
    $network[ip].network.each_key {|network_ip|
      $network[network_ip].delete()
    }
    #del network from gui elements
    $network[$network[ip].map].del_net(ip) unless $network[$network[ip].map] == nil
    #del network from network list
    $network.delete ip
  end
end

#del_node_def_exception_list(str) ⇒ Object

del node definition from exception list



104
105
106
# File 'lib/main.rb', line 104

def del_node_def_exception_list(str)
    $node_exception_list.delete(str)
end

#del_selected_contact_entry(win) ⇒ Object



400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
# File 'lib/gui/sub/contact_frame.rb', line 400

def del_selected_contact_entry(win)
	if @contact_view.selection.selected
firstname=@contact_view.selection.selected[0]
lastname=@contact_view.selection.selected[1]
if !Contact::used?(firstname, lastname)
    @contact_view.model.remove(@contact_view.selection.selected)
  		    Contact::del_contact(firstname, lastname)
    if Contact::contact_nb_entry() == 0
	    if @cb_mail
   			@cb_mail.set_sensitive(false)
	    	@cb_im.set_sensitive(false)
		@cb_sms.set_sensitive(false)
   			@entry_mail_button.set_sensitive(false)
		@entry_im_button.set_sensitive(false)
		@entry_sms_button.set_sensitive(false)
	    end
    end
else
	errorEntry(win, "Contact #{firstname} #{lastname} is in used #{$contact["#{firstname}|#{lastname}"].nb_use} time(s)")
end
	end
end

#del_selected_nodeObject

delete selected node(s)



365
366
367
368
369
370
371
372
373
374
375
376
# File 'lib/main.rb', line 365

def del_selected_node()
  mapp=get_map()
  if $map != nil
    nodes=[]
    $network[mapp].get_node().each_value {|node|
      if node.node_view.selected?()
        nodes.push(node)
      end
    }
    verify_delnodewin(nodes) unless nodes.size() == 0
  end
end

#delnodewinObject

delete node window



668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
# File 'lib/gui/adddelnode.rb', line 668

def delnodewin()
    if $win == nil
  	    return
    end

    delwin=Gtk::Window.new
    delwin.set_transient_for($win)
    delwin.set_title("Node deleting")
    delwin.set_size_request(250, 160)
    delwin.set_modal(true)

    delwin.signal_connect("key_press_event") {|w,e|
      if e.keyval == Gdk::Keyval::GDK_Escape
			delwin.destroy
      end
    }

    frame = Gtk::Frame::new("Del Node")
    frame.border_width=10
    frame.show
    vbox_root=Gtk::VBox::new
    vbox_root.show
    delwin.add vbox_root
    vbox_root.add frame
    vbox = Gtk::VBox.new
    vbox.show
    frame.add vbox

    table = Gtk::Table.new(3,2,false)
	 table.set_row_spacings(5)
	 table.set_size_request(-1,15)
    table.show

    label_type = Gtk::Label.new "Type"
    label_type.show
	 combo_type=Gtk::ComboBox.new
	 combo_type.append_text("Host")
	 combo_type.append_text("Network")
	 combo_type.set_active(0)
  	 combo_type.show

    table.attach(label_type,0,1,0,1)
    table.attach(combo_type,1,2,0,1)

    label_value = Gtk::Label.new "Value"
    label_value.show
	 combo_value=Gtk::ComboBox.new
	 $host.each_value do |node|
		 combo_value.append_text(node.ip)
	 end
	 combo_value.set_active(0)
  	 combo_value.show

    table.attach(label_value,0,1,1,2)
    table.attach(combo_value,1,2,1,2)
	
	combo_type.signal_connect("changed") do |combo|
		case combo.active_text
			when "Host" then
				for ind in 0..$network.size()-2
					combo_value.remove_text(0)
				end
				$host.each_value do |node|
					combo_value.append_text(node.ip)
	 			end
				combo_value.set_active(0)
			when "Network" then
				for ind in 0..$host.size()-1
					combo_value.remove_text(0)
				end
				#need to test in which map we are
				network_list=[]
				#contain path to map in which we are
				map_list=[]
				map_current=get_map()	
				begin
				  map_list.push map_current
				  map_current=$network[map_current].map
				end until map_current == nil

				$network.each_value do |node|
					 network_list.push(node.ip)
	 			end
	 			(network_list - map_list).each do |val|
                  combo_value.append_text(val)
	 			end
				combo_value.set_active(0)
		end
 	end
    del_button = Gtk::Button.new(Gtk::Stock::REMOVE)
    del_button.show
    del_button.signal_connect("clicked") {
		case combo_type.active_text
			when "Host" then
			    if combo_value.active_text != nil
    				if verify_delnodewin($host[combo_value.active_text]) == 1
   	            combo_value.remove_text(combo_value.active)
	    				combo_value.set_active(0)
					end
				end
			when "Network" then
			    if combo_value.active_text != nil
					if verify_delnodewin($network[combo_value.active_text]) == 1
                  combo_value.remove_text(combo_value.active)
      				combo_value.set_active(0)
					end
  				end
		end
    }

    close_button = Gtk::Button.new(Gtk::Stock::CLOSE)
    close_button.show
    close_button.signal_connect("clicked") {
  	    delwin.destroy 
    }

	 bbox =Gtk::HBox::new(FALSE, 10)
	 bbox.border_width=10
	 bbox.show

	 del_button.set_flags(Gtk::Widget::CAN_DEFAULT)
	 bbox.pack_start(del_button, TRUE, TRUE, 0)
	 close_button.set_flags(Gtk::Widget::CAN_DEFAULT)
	 bbox.pack_start(close_button, TRUE, TRUE, 0)

	 vbox.pack_start(table, FALSE, TRUE)
	 separator = Gtk::HSeparator::new()
	 separator.show
	 vbox_root.pack_start(separator, FALSE, TRUE, 0)
	 vbox_root.pack_start(bbox, FALSE, TRUE, 0)

   delwin.show
end

#edit_contact_entry(ref) ⇒ Object



45
46
47
# File 'lib/gui/sub/contact_frame.rb', line 45

def edit_contact_entry(ref)
	add_contact_entry_details(false, ref)
end

#errorEntry(win, ent) ⇒ Object

error window



88
89
90
91
92
93
94
95
96
97
98
99
100
101
# File 'lib/gui/adddelnode.rb', line 88

def errorEntry(win, ent)
      lbl="You have to fill at least IP or DNS name"
      if ent != ""
	      lbl="Error: '#{ent}'"
      end
      dialog = Gtk::MessageDialog.new(win, Gtk::Dialog::DESTROY_WITH_PARENT,
                        	Gtk::MessageDialog::ERROR,
                        	Gtk::MessageDialog::BUTTONS_OK,
                        	lbl)

	dialog.set_icon("#{PIXMAP_PATH}/logo_icon.png")
	dialog.run
	dialog.destroy
end

#exist_host(ip) ⇒ Object

return true if host ip addr is known need: ip



429
430
431
# File 'lib/main.rb', line 429

def exist_host(ip)
  return $host[ip] != nil
end

#exist_monitoring_thread(str) ⇒ Object

check if corresponding str name exists as a thread



243
244
245
# File 'lib/main.rb', line 243

def exist_monitoring_thread(str)
  return $thread_list[str] != nil
end

#exist_network(ip) ⇒ Object

return true if network ip addr is known need: ip



466
467
468
# File 'lib/main.rb', line 466

def exist_network(ip)
  return $network[ip] != nil
end

#fill_contact_entryObject



277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
# File 'lib/gui/sub/contact_frame.rb', line 277

def fill_contact_entry()
	window=Gtk::Window.new
	window.set_modal(true)

 	window.set_title("Fill Contact using LDAP directory")
 	window.set_size_request(360, 240)

	window.signal_connect("key_press_event") {|w,e|
      	if e.keyval == Gdk::Keyval::GDK_Escape
	window.destroy
       end
 	}

	frame = Gtk::Frame::new
	frame.border_width=10
	frame.show
	vbox_root=Gtk::VBox::new
	vbox_root.show
	window.add vbox_root
	vbox_root.add frame

	vbox = Gtk::VBox.new
	vbox.show
	frame.add vbox

	table = Gtk::Table.new(3,2,false)
	table.show

	label_host = Gtk::Label.new "Host"
	label_host.show
	entry_host = Gtk::Entry.new			
	entry_host.show
	table.attach(label_host,0,1,0,1)
	table.attach(entry_host,1,2,0,1)

	label_port = Gtk::Label.new "Port"
	label_port.show
	entry_port = Gtk::Entry.new
	entry_port.set_text(LDAP::LDAP_PORT.to_s)
	entry_port.show
	table.attach(label_port,0,1,1,2)
	table.attach(entry_port,1,2,1,2)

	label_base = Gtk::Label.new "Base"
	label_base.show
	entry_base = Gtk::Entry.new			
	entry_base.show
	table.attach(label_base,0,1,2,3)
	table.attach(entry_base,1,2,2,3)
	

	bbox =Gtk::HBox::new(FALSE, 10)
	bbox.border_width=10
	bbox.show

	ok_button = Gtk::Button.new(Gtk::Stock::REFRESH)
	ok_button.show
	ok_button.signal_connect("clicked") {
host = entry_host.text
port = entry_port.text
#SSLPORT = LDAP::LDAPS_PORT
base = entry_base.text
if host!="" && port!="" && base!=""
   scope = LDAP::LDAP_SCOPE_SUBTREE
   filter = '(objectclass=person)'
   attrs = ['cn', 'sn', 'givenName', 'mail', 'telephoneNumber', 'mobile', 'title', 'o']

   begin
	   Thread.start {
	      conn = LDAP::Conn.new(host, port.to_i)
	      #conn.bind(dn=nil, password=nil, method=LDAP::LDAP_AUTH_SIMPLE)
	      #conn.perror("bind")
	      conn.search(base, scope, filter, attrs) { |entry|
		 # print distinguished name
		 #p entry.dn
		 # print all attribute names
		 #p entry.attrs
		 # print values of attribute 'sn'
		 # print entry as Hash
		 $log.debug(entry.to_hash)
		 firstname=entry.to_hash["givenName"]
		 lastname=entry.to_hash["sn"]
		 #seems all values are returned in an array
		 if firstname && lastname && !Contact::contact_exist?(firstname.first, lastname.first)
			 Contact::add_contact(firstname.first, lastname.first, (entry.to_hash["mail"] && entry.to_hash["mail"].first) || "", (entry.to_hash["telephoneNumber"] && entry.to_hash["telephoneNumber"].first) || "",  (entry.to_hash["mobile"] && entry.to_hash["mobile"].first) || "",  "", "", (entry.to_hash["title"] && entry.to_hash["title"].first) || "", (entry.to_hash["o"] && entry.to_hash["o"].first) || "", "", "")
			 Gtk.thread_protect do
			 	if @contact_view
		   	      		iter = @contact_view.model.append
		   	      		iter[0] = firstname.first
			      		iter[1] = lastname.first
			 	end
			 end
		 end
	   }
   }
   rescue LDAP::ResultError
	   $log.error("Can't search for contact with given arguments")
   rescue Exception => msg
	   $log.error("LDAP searching error #{msg}")
   end
   #conn.perror("search")
   #conn.unbind
end
	}

	cancel_button = Gtk::Button.new(Gtk::Stock::CLOSE)
	cancel_button.show
	cancel_button.signal_connect("clicked") {
window.destroy
	}

	ok_button.set_flags(Gtk::Widget::CAN_DEFAULT)
	bbox.pack_start(ok_button, TRUE, TRUE, 0)
	cancel_button.set_flags(Gtk::Widget::CAN_DEFAULT)
	bbox.pack_start(cancel_button, TRUE, TRUE, 0)		
	vbox.add table
	separator = Gtk::HSeparator::new()
	separator.show
	vbox_root.pack_start(separator, FALSE, TRUE, 0)
	vbox_root.pack_start(bbox, FALSE, TRUE, 0)
	window.show
end

#fill_ip_str(ip) ⇒ Object

fill ip str with prepending zero chars



302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
# File 'lib/main.rb', line 302

def fill_ip_str(ip)
  if ip.nil?
    return nil
  end
  table=ip.split(/\./)
  if table.length != 4
    return nil
  end
  ip_tmp=""
  for i in 0..table.size-1
    ip_tmp+="0"*(3-table[i].length)+table[i]
    ip_tmp+="." unless i==table.size-1
  end
  return ip_tmp
end

#find_extension(file) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/gui/color_macro.rb', line 24

def find_extension (file)
if FileTest.exist?("#{PIXMAP_PATH}/#{file}.png")
    return "#{file}.png"
  elsif FileTest.exist?("#{PIXMAP_PATH}/#{file}.gif")
      return "#{file}.gif"
    elsif FileTest.exist?("#{PIXMAP_PATH}/#{file}.jpg")
        return "#{file}.jpg"
      elsif FileTest.exist?("#{PIXMAP_PATH}/#{file}.xpm")
          return "#{file}.xpm"
	else
          return "null"
        end
end

#find_manufacturer(mac) ⇒ Object

Return nic manufacturer based on OUI



111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
# File 'lib/cmd_parse.rb', line 111

def find_manufacturer (mac)
	if FileTest.exist?("#{CONF_DIR}/oui.txt")

		if defined?($mac_manufacturer)
			if $mac_manufacturer[mac] != ""
				return $mac_manufacturer[mac]
			end
		else
			$mac_manufacturer=Hash.new
		end

		manufacturer_name="unknown"
		f=File.open("#{CONF_DIR}/oui.txt","r")
		begin
		while (line = f.readline)
        line.chomp
        if line.match("^#{mac}")
			result_t=line.split(/\s+/)
			manufacturer_name=result_t[1]
		  end
    	end
		rescue EOFError
    		f.close
		end
	   $mac_manufacturer[mac]=manufacturer_name
      return manufacturer_name
	else
		$log.warn("you need to download OUIs list, see pref")
		return nil
	end
end

#find_separated_value_from_two_lines(l1, l2, attribute) ⇒ Object

return the value corresponding to the good attribute. a bug in wmic does not return only requested attributes



6
7
8
9
10
11
12
13
14
15
16
# File 'lib/monitor/client/wmi/wmi.rb', line 6

def find_separated_value_from_two_lines(l1, l2, attribute)
	if (l1 == nil) || (l2 == nil)
		return nil
	end
	attrt=l1.split('|')
	valuet=l2.split('|')
	if attrt.index(attribute) == nil
		return nil
	end
	return valuet[attrt.index(attribute)]
end

#findnodewinObject



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
# File 'lib/gui/find_node_window.rb', line 7

def findnodewin()

win_title="Find node"

node_type=["Host", "Network", "Any"]
search_host=["IP", "Status", "Mac", "Dns name", "Netbios name", "Description", "Type","OS" ]
search_network=["IP", "Status", "Name", "Dns domain", "Netbios domain",  "Description", "Type","OS" ]
search_any=["IP", "Status","Dns name","Netbios name", "Description", "Type","OS"]

win = Gtk::Window.new
win.set_transient_for($win)
win.set_title win_title
win.set_size_request(600,415)

vbox_root=Gtk::VBox.new
vbox_root.show
win.add vbox_root


frame = Gtk::Frame::new
frame.border_width=10
frame.show
vbox_root.add frame

vbox_frame=Gtk::VBox.new
vbox_frame.show
frame.add vbox_frame

hhbox_root=Gtk::HBox.new
hhbox_root.set_size_request(-1,10)
hhbox_root.show
hhbox = Gtk::HBox.new
hhbox.show
hhbox_root.add hhbox

vbox_frame.add hhbox_root

node_type_combo = Gtk::ComboBox.new
node_type_combo.set_size_request(60,-1)
node_type.each do |val|
	node_type_combo.append_text(val)
end
node_type_combo.set_active(0)
node_type_combo.show
hhbox.add node_type_combo

type_choice = Gtk::ComboBox.new()
type_choice.set_size_request(100,-1)
search_host.each do |shost|
	type_choice.append_text(shost)
end
type_choice.set_active(0)
type_choice.show
hhbox.add type_choice

entry_glb=Gtk::Entry.new
interfaces_table = local_interface()
if interfaces_table.size > 0
   ip_of_first_interface = interfaces_table[0][0]
   entry_glb.set_text ip_of_first_interface
end
entry_glb.show
hhbox.add entry_glb

vvbox=Gtk::VButtonBox.new
vvbox.show
hhbox_root.add vvbox
button_find=Gtk::Button.new(Gtk::Stock::FIND)
button_find.set_flags(Gtk::Widget::CAN_DEFAULT)
button_find.show
vvbox.add button_find

entry_glb.signal_connect("key_press_event") {|w,e|
  if e.keyval == Gdk::Keyval::GDK_Return
    button_find.clicked
  end
}

clist = Gtk::CList::new(search_host)
clist.show
clist.set_size_request 500,280
scroll = Gtk::ScrolledWindow.new(nil, nil)
scroll.border_width=2
scroll.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC)  
vbox_frame.pack_start(scroll, true, true, 0)
scroll.show
scroll.add(clist)


bbox =Gtk::HBox::new(FALSE, 10)
bbox.border_width=10
bbox.show

button_clear=Gtk::Button.new(Gtk::Stock::CLEAR)
button_clear.show
button_close=Gtk::Button.new(Gtk::Stock::CLOSE)
button_close.show

button_clear.set_flags(Gtk::Widget::CAN_DEFAULT)
bbox.pack_start(button_clear, TRUE, TRUE, 0)
button_close.set_flags(Gtk::Widget::CAN_DEFAULT)
bbox.pack_start(button_close, TRUE, TRUE, 0)

separator = Gtk::HSeparator::new()
separator.show
vbox_root.pack_start(separator, FALSE, TRUE, 0)
vbox_root.pack_start(bbox, FALSE, TRUE, 0)


clist.signal_connect("cursor-changed") { |s, event|
	iter = s.selection.selected
	ip=s.model.get_value(iter,1)
	if $network.has_key?(ip)
		set_map($network[ip].map)
		$network[ip].node_view.select()
	else
		if $host[ip] != nil
			set_map($host[ip].map)
			$host[ip].node_view.select()
		end
	end
}
win.show

button_close.signal_connect("clicked") {
  win.destroy
}

button_clear.signal_connect("clicked") {
	clist.clear
	win.set_title win_title
}

button_find.signal_connect("clicked") {
  clist.clear
  nb_node_find=0

  node_list=nil
  type=node_type_combo.active_text
	if type=="Network"
		node_list=$network
	elsif type=="Host"
		node_list=$host
	else
	#any type
		node_list=$host.merge($network)
	end

  case type_choice.active_text
  when "IP" then
    node_list.each_key {|ip|
		if entry_glb.text==""
			if ip==""
				if type == "Any"
					#remove MAC addr from host or name from network result array
					array_without_mac=node_list[ip].to_t
					array_without_mac.delete_at(2)
					clist.append(array_without_mac)
				else
					clist.append(node_list[ip].to_t)
				end
				nb_node_find+=1
			end
		elsif ip.index(entry_glb.text) != nil
			if type == "Any"
				array_without_mac=node_list[ip].to_t
				array_without_mac.delete_at(2)
				clist.append(array_without_mac)
			else
				clist.append(node_list[ip].to_t)
			end
			nb_node_find+=1
      end
    }
  when "Mac" then
    node_list.each_key {|ip|
		if entry_glb.text==""
			if (node_list[ip].mac!=nil) && (node_list[ip].mac==Node::NOARP_PROPERTY)
				clist.append(node_list[ip].to_t)
				nb_node_find+=1
			end
		elsif (node_list[ip].mac!=nil) && (node_list[ip].mac.index(entry_glb.text.upcase)!=nil)
			clist.append(node_list[ip].to_t)
			nb_node_find+=1
      end
    }
  when "Name" then
    node_list.each_key {|ip|
		if entry_glb.text==""
			if  node_list[ip].name==Node::NONAME_PROPERTY
				clist.append(node_list[ip].to_t)
				nb_node_find+=1
			end
		elsif node_list[ip].name.index(entry_glb.text) != nil
			clist.append(node_list[ip].to_t)
			nb_node_find+=1
      end
    }
  when "Dns name" then
    node_list.each_key {|ip|
		if entry_glb.text==""
			if node_list[ip].dns_name==Node::NONAME_PROPERTY
				if type == "Any"
					#remove MAC addr from host or name from network result array
					array_without_mac=node_list[ip].to_t
					array_without_mac.delete_at(2)
					clist.append(array_without_mac)
				else
					clist.append(node_list[ip].to_t)
				end
				nb_node_find+=1
			end
		elsif node_list[ip].dns_name.index(entry_glb.text) != nil
				if type == "Any"
					#remove MAC addr from host or name from network result array
					array_without_mac=node_list[ip].to_t
					array_without_mac.delete_at(2)
					clist.append(array_without_mac)
				else
					clist.append(node_list[ip].to_t)
				end
			nb_node_find+=1
      end
    }
  when "Dns domain" then
    node_list.each_key {|ip|
		if entry_glb.text==""
			if  node_list[ip].dns_domain==Node::NONAME_PROPERTY
				clist.append(node_list[ip].to_t)
				nb_node_find+=1
			end
		elsif node_list[ip].dns_domain.index(entry_glb.text) != nil
			clist.append(node_list[ip].to_t)
			nb_node_find+=1
      end
    }
  when "Netbios name" then
    node_list.each_key {|ip|
		if entry_glb.text==""
			if  node_list[ip].netbios_name==Node::NONAME_PROPERTY
				if type == "Any"
					#remove MAC addr from host or name from network result array
					array_without_mac=node_list[ip].to_t
					array_without_mac.delete_at(2)
					clist.append(array_without_mac)
				else
					clist.append(node_list[ip].to_t)
				end
				nb_node_find+=1
			end
		elsif node_list[ip].netbios_name.index(entry_glb.text) != nil
				if type == "Any"
					#remove MAC addr from host or name from network result array
					array_without_mac=node_list[ip].to_t
					array_without_mac.delete_at(2)
					clist.append(array_without_mac)
				else
					clist.append(node_list[ip].to_t)
				end
			nb_node_find+=1
      end
    }
  when "Netbios domain" then
    node_list.each_key {|ip|
		if entry_glb.text==""
			if  node_list[ip].netbios_domain==Node::NONAME_PROPERTY
				clist.append(node_list[ip].to_t)
				nb_node_find+=1
			end
		elsif node_list[ip].netbios_domain.index(entry_glb.text) != nil
			clist.append(node_list[ip].to_t)
			nb_node_find+=1
      end
    }
  when "Status" then
    node_list.each_key {|ip|
      if $status[$status_value.index(node_list[ip].status)] == entry_glb.active_text
				if type == "Any"
					#remove MAC addr from host or name from network result array
					array_without_mac=node_list[ip].to_t
					array_without_mac.delete_at(2)
					clist.append(array_without_mac)
				else
					clist.append(node_list[ip].to_t)
				end
			nb_node_find+=1
      end
    }
  when "Description" then
    node_list.each_key {|ip|
		if entry_glb.text==""
			if  node_list[ip].description==Node::NODESCR_PROPERTY
				if type == "Any"
					#remove MAC addr from host or name from network result array
					array_without_mac=node_list[ip].to_t
					array_without_mac.delete_at(2)
					clist.append(array_without_mac)
				else
					clist.append(node_list[ip].to_t)
				end
				nb_node_find+=1
			end
		elsif node_list[ip].description.index(entry_glb.text) != nil
				if type == "Any"
					#remove MAC addr from host or name from network result array
					array_without_mac=node_list[ip].to_t
					array_without_mac.delete_at(2)
					clist.append(array_without_mac)
				else
					clist.append(node_list[ip].to_t)
				end
			nb_node_find+=1
      end
    }
  when "Type" then
    node_list.each_key {|ip|
      if node_list[ip].type == entry_glb.active_text
				if type == "Any"
					#remove MAC addr from host or name from network result array
					array_without_mac=node_list[ip].to_t
					array_without_mac.delete_at(2)
					clist.append(array_without_mac)
				else
					clist.append(node_list[ip].to_t)
				end
			nb_node_find+=1
      end
    }
  when "OS" then
    node_list.each_key {|ip|
      if node_list[ip].os == entry_glb.active_text
				if type == "Any"
					#remove MAC addr from host or name from network result array
					array_without_mac=node_list[ip].to_t
					array_without_mac.delete_at(2)
					clist.append(array_without_mac)
				else
					clist.append(node_list[ip].to_t)
				end
			nb_node_find+=1
      end
    }
	end

    win.set_title(win_title+" - #{nb_node_find} result(s)")

}

win.signal_connect("key_press_event") {|w,e|
  if e.keyval == Gdk::Keyval::GDK_Escape
    win.destroy
  end
}

node_type_combo.signal_connect("changed") {|entry|
	case entry.active_text
	when "Host" then
		search_network.each do |sh|
			type_choice.remove_text(0)
		end
		search_host.each do |sh|
			type_choice.append_text(sh)
		end
		type_choice.set_active(0)
		clist.changed_all_column_name(search_host)
	when "Network" then
		search_host.each do |sh|
			type_choice.remove_text(0)
		end

		search_network.each do |sn|
			type_choice.append_text(sn)
		end
		type_choice.set_active(0)
		clist.changed_all_column_name(search_network)
	else
		#host & network have same number of entry in array type
		search_host.each do |sh|
			type_choice.remove_text(0)
		end

		search_any.each do |sn|
			type_choice.append_text(sn)
		end
		type_choice.set_active(0)
		clist.changed_all_column_name(search_any)
	end
	clist.clear
	win.set_title win_title
}

type_choice.signal_connect("changed") {|cbox|
  case cbox.active_text
  when "Type" then
    entry_glb.hide
    entry_glb.destroy
    entry_glb=Gtk::ComboBox.new
	 $type.each do |t|
		entry_glb.append_text(t)
	 end
	 entry_glb.set_active(0)
    entry_glb.show
    hhbox.add entry_glb
  when "OS" then
    entry_glb.hide
    entry_glb.destroy
    entry_glb=Gtk::ComboBox.new
	 $os.each do |os|
		entry_glb.append_text(os)
	 end
	 entry_glb.set_active(0)
    entry_glb.show
    hhbox.add entry_glb
  when "Status" then
    entry_glb.hide
    entry_glb.destroy
    entry_glb=Gtk::ComboBox.new
	 $status.each do |st|
		entry_glb.append_text(st)
	 end
	 entry_glb.set_active(0)
    entry_glb.show
    hhbox.add entry_glb
   else
      entry_glb.hide
      entry_glb.destroy
      entry_glb=Gtk::Entry.new
      entry_glb.show
      hhbox.add entry_glb
  end
}
end

#get_changelog(version) ⇒ Object

get changelog from version arg



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/gui/update_window.rb', line 6

def get_changelog(version)
  changelog_text=""
  #changelog file name is changelog-last_version_file_name
  changelog_base_name="changelog-"

  begin
  Net::HTTP.start(GNMS_PROJECT_SERVER, 80) do |http|
	  response,=http.get('/'+GNMS_PROJECT_URL+'/'+changelog_base_name+version)
	  response.body.each do |str|
		changelog_text=changelog_text+"#{str}"
	  end
  end
  rescue
  end
  if changelog_text == ""
	return "No changelog available"
  else
	return changelog_text
  end
end

#get_color_from_status(status) ⇒ Object

return a color based on the node sev status



176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
# File 'lib/main.rb', line 176

def get_color_from_status(status)
  case status
  when "CRITICAL"
    return $red
  when "MAJOR"
    return $orange
  when "WARNING"
    return $yellow
  when "MINOR"
    return $blue
  when "NORMAL"
    return $green
  when "UNMANAGED"
    return $grey
  when "UNKNOWN"
    return $purple
  end
end

#get_default_map_heightObject

return screen height



354
355
356
357
358
359
360
# File 'lib/main.rb', line 354

def get_default_map_height()
  if $config.default_height == nil || $config.default_height == ""
    return Gdk::screen_height/2
  else
    return $config.default_height.to_i
  end
end

#get_default_map_widthObject

return screen width



343
344
345
346
347
348
349
# File 'lib/main.rb', line 343

def get_default_map_width()
  if $config.default_width == nil || $config.default_width == ""
    return Gdk::screen_width/2
  else
    return $config.default_width.to_i
  end
end

#get_level_from_status(status) ⇒ Object

convert status to level

can return a level or '' if not convert or "UNKNOWN", "UNMANAGED" if "UNMANAGED"


199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
# File 'lib/main.rb', line 199

def get_level_from_status(status)
  case status
  when "UNMANAGED"
    return "UNMANAGED"
  when "CRITICAL"
    return "PANIC"
  when "MAJOR"
    return "ALERT"
  when "WARNING"
    return "ERR"
  when "MINOR"
    return "WARN"
  when "NORMAL"
    return "INFO"
  else
    return ""
  end
end

#get_mac_manufacturer_listObject

download mac manufacturer list



67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
# File 'lib/cmd_parse.rb', line 67

def get_mac_manufacturer_list()
  if !mac_manufacturer_list_exist?()
    ieee_addr="standards.ieee.org"
    ieee_url="/develop/regauth/oui/oui.txt"
    local_file_path="#{CONF_DIR}"
    local_file_name="oui.txt"
    if RUBY_VERSION.match("^1\.8")
      Net::HTTP.version_1_1
    end
    tf=Tempfile.new(local_file_name)
    begin
      Net::HTTP.start(ieee_addr, 80) do |http|
        response,=http.get(ieee_url)
        response.body.split("\n").each do |str|
          str.chomp
          if str.match('base\s16')
            #line syntax is 'XXXXXX     (base 16)            name'
            str.scan(/(\w+)\s+\([^)]+\)\s+(.+)/) do |mac,manufacturer|
              tf.write "#{mac}\t#{manufacturer}\n"
            end
          end
        end
      end
    rescue Exception => msg
      $log.error(msg.backtrace.join("\n"))
      tf.close(true)
      return -1
    end
  end
  tf.close
  FileUtils.move(tf.path, "#{local_file_path}/#{local_file_name}")
  return 0
end

#get_mapObject

return current network map



535
536
537
538
539
540
541
# File 'lib/main.rb', line 535

def get_map()
  if $map == nil
    return ROOTMAPADDR
  else
    return $map
  end
end

#get_map_heightObject

return window map height or default value



332
333
334
335
336
337
338
# File 'lib/main.rb', line 332

def get_map_height()
  if $win and $win.window != nil
    return $win.window.geometry[3]
  else
    return $root_height
  end
end

#get_map_widthObject

return window map width or default value



321
322
323
324
325
326
327
# File 'lib/main.rb', line 321

def get_map_width()
  if $win and $win.window != nil
    return $win.window.geometry[2]
  else
    return $root_width
  end
end

#get_networkObject

return table of network ip



508
509
510
511
512
513
514
515
516
517
518
# File 'lib/main.rb', line 508

def get_network()
  hnet=[]
  $network.each_value {|node|
    #if node.name?
    #	hnet.push node.name
    #else
    hnet.push node.ip
    #end
  }
  return hnet
end

#get_snmp_contact(node) ⇒ Object

Return contact of an host



134
135
136
137
138
139
# File 'lib/monitor/client/snmp/snmp.rb', line 134

def get_snmp_contact(node)
  if node.status == CRITICAL
    return "Error"
  end
  return get_snmp_OID(node, "sysContact.0")
end

#get_snmp_description(node) ⇒ Object

Return the description of an host



144
145
146
147
148
149
# File 'lib/monitor/client/snmp/snmp.rb', line 144

def get_snmp_description(node)
  if node.status == CRITICAL
    return "Error"
  end
  return get_snmp_OID(node, "sysDescr.0")
end

#get_snmp_location(node) ⇒ Object

Return location of an host



124
125
126
127
128
129
# File 'lib/monitor/client/snmp/snmp.rb', line 124

def get_snmp_location (node)
  if node.status == CRITICAL
    return "Error"
  end
  return get_snmp_OID(node, "sysLocation.0")
end

#get_snmp_name(host) ⇒ Object

Return the name of a node



154
155
156
157
158
159
# File 'lib/monitor/client/snmp/snmp.rb', line 154

def get_snmp_name(host)
  if node.status == CRITICAL
    return "Error"
  end
  return get_snmp_OID(node, "sysName.0")
end

#get_snmp_OID(node, oid) ⇒ Object

return the value of the entry



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/monitor/client/snmp/snmp.rb', line 10

def get_snmp_OID(node, oid)

  #get values from node network
  version=node.get_default_inherit_snmp_version()
  port=node.get_default_inherit_snmp_port()
  timeout=node.get_default_inherit_snmp_timeout()
  retr=node.get_default_inherit_snmp_retry()

  community_read = $config.read_community
  community_write = $config.write_community
  if node.("snmp")
    community_read, community_write = node.("snmp")
  end

  begin
    #print "get_snmp_OID: ", node.ip, " ", community_read, " ", community_write, " ", get_snmp_version(version), " ", port.to_i, " ", timeout.to_i, " ", retr.to_i,"\n"
    SNMP::Manager.open(:Host => node.ip, :Community => community_read, :WriteCommunity => community_write, :Version => get_snmp_version(version), :Port => port.to_i, :Timeout => timeout.to_i, :Retries => retr.to_i) do |manager|
      response = manager.get(oid)
      response.each_varbind do |vb|
        return vb.value.to_s
      end
    end
  rescue SNMP::RequestTimeout    
    $log.debug("Error in get_snmp_OID: #{node.ip} not responding")
    return "Error"  
  rescue Exception => msg
    $log.error("Error in get_snmp_OID: #{msg}")
    return "Error"
  end
end

#get_snmp_uptime(node) ⇒ Object

Return uptime of an host



114
115
116
117
118
119
# File 'lib/monitor/client/snmp/snmp.rb', line 114

def get_snmp_uptime(node)
  if node.status == CRITICAL
    return "Error"
  end
  return get_snmp_OID(node, "sysUpTime.0")
end

#get_snmp_version(str) ⇒ Object

return current snmp version from version str



165
166
167
168
169
170
171
# File 'lib/main.rb', line 165

def get_snmp_version(str)
  if str == SNMPv2
    return :SNMPv2c
  else
    return :SNMPv1
  end
end

#get_status_from_level(level) ⇒ Object

map syslog level to node status



221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
# File 'lib/main.rb', line 221

def get_status_from_level(level)
  case level
  when "UNMANAGED"
    return "UNMANAGED"
  when "PANIC"
    return "CRITICAL"
  when "ALERT"
    return "MAJOR"
  when "ERR"
    return "WARNING"
  when "WARN"
    return "MINOR"
  when "INFO"
    return "NORMAL"
  else
    return "UNKNOWN"
  end
end

#get_system_inforObject

get system information



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/cmd_parse.rb', line 8

def get_system_infor()
    sysinfor = Hash.new()
    sysinfor["cpu" => "","Memory" =>"","hostname" => "","OS" => ""]
    value=`cat /proc/cpuinfo | grep 'model name'`
    value=value.match(/\:\s+(\w+.*)/)
    if value != nil
       sysinfor["cpu"]=value[1]
    end
    value=`cat /proc/meminfo | grep 'MemTotal'`
    value=value.match(/\:\s+(\d+)\s+(\w+)/)
    if value !=nil
       if (value[2] == "kB") and isInteger(value[1])
         if value[1].to_f >= 1024
           val = value[1].to_f / 1024 / 1024
	   sysinfor["Memory"]="#{sprintf "%.1f",val} G"
	 else
           val = value[1].to_f / 1024
	   sysinfor["Memory"]="#{sprintf "%.1f",val} M"
	 end
       else
         sysinfor["Memory"]=sprintf "%.1f",value[1]
       end
    end   
    value=`hostname`
    sysinfor["hostname"]=value.chomp

    value=`cat /proc/version`    
    sysinfor["OS"]=value.chomp

    value=`df -h`
    disk_size=0
    flag=false
    #parsing the output of command "df -h"
    value.each_line{|s|
          temp=s.match(/\/dev\//)
          if temp !=nil
          flag=true
          end
          temp=s.match(/\s+(\d+[\w])\s+\w+\.?\w*\s+\w+\.?\w*\s+\d+\.?\d*\%/)
          if temp !=nil && flag
             if temp[1].gsub!(/M/){|s|}!=nil
                 temp1=temp[1].gsub("M","")
                 temp2=temp1.to_f
                 temp2=temp2/1024
             else
                 temp1=temp[1].gsub("M","")
                 temp2=temp1.to_f
             end
             disk_size=disk_size+temp2
             flag=false
          end
    } 
    sysinfor["Disk Size"]="#{sprintf "%.1f",disk_size} G"
    return sysinfor
end

#get_wmi_boot_state(login, password, host) ⇒ Object

return the bootup state using a wmi request



36
37
38
39
# File 'lib/monitor/client/wmi/wmi.rb', line 36

def get_wmi_boot_state(, password, host)
	resultt=wmi_request(, password, host, "select BootupState from Win32_ComputerSystem")
	return find_separated_value_from_two_lines(resultt[1], resultt[2], "BootupState")	
end

#get_wmi_description(login, password, host) ⇒ Object

return the ComputerSystem description using a wmi request



22
23
24
25
26
27
28
29
30
# File 'lib/monitor/client/wmi/wmi.rb', line 22

def get_wmi_description(, password, host)
	resultt=wmi_request(, password, host, "select Description from Win32_ComputerSystem")

	#format is as below
	#CLASS: Win32_ComputerSystem
	#Description|Name
	#AT/AT COMPATIBLE|KOMA-PC
	return find_separated_value_from_two_lines(resultt[1], resultt[2], "Description")
end

#get_wmi_domain(login, password, host) ⇒ Object

return domain name using a wmi request



135
136
137
138
# File 'lib/monitor/client/wmi/wmi.rb', line 135

def get_wmi_domain(, password, host)
	resultt=wmi_request(, password, host, "select Domain from Win32_ComputerSystem")
	return find_separated_value_from_two_lines(resultt[1], resultt[2], "Domain")	
end

#get_wmi_name(login, password, host) ⇒ Object

return host name using a wmi request



127
128
129
130
# File 'lib/monitor/client/wmi/wmi.rb', line 127

def get_wmi_name(, password, host)
	resultt=wmi_request(, password, host, "select Name from Win32_ComputerSystem")
	return find_separated_value_from_two_lines(resultt[1], resultt[2], "Name")	
end

#get_wmi_nb_proc(login, password, host) ⇒ Object

return the number of processor on the host using a wmi request



75
76
77
78
# File 'lib/monitor/client/wmi/wmi.rb', line 75

def get_wmi_nb_proc(, password, host)
	resultt=wmi_request(, password, host, "select NumberOfProcessors from Win32_ComputerSystem")
	return find_separated_value_from_two_lines(resultt[1], resultt[2], "NumberOfProcessors")
end

#get_wmi_os(login, password, host) ⇒ Object

return the concatenation of OS and SP level using a wmi request



91
92
93
94
95
96
97
98
99
100
101
102
# File 'lib/monitor/client/wmi/wmi.rb', line 91

def get_wmi_os(, password, host)
	resultt=wmi_request(, password, host, "select Name,CSDVersion from Win32_OperatingSystem")
	val1=find_separated_value_from_two_lines(resultt[1], resultt[2], "Name")
	val2=find_separated_value_from_two_lines(resultt[1], resultt[2], "CSDVersion")
	if !val1
		return nil
	end
	if !val2 || (val2 == "")
		val2=0
	end
	return "#{val1} SP#{val2}"
end

#get_wmi_product_type(login, password, host) ⇒ Object

return product type using a wmi request



107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
# File 'lib/monitor/client/wmi/wmi.rb', line 107

def get_wmi_product_type(, password, host)
#1 Work Station
#2 Domain Controller
#3 Server
#seems it does not exist in windows 2000 server
	resultt=wmi_request(, password, host, "select ProductType from Win32_OperatingSystem")
	value=find_separated_value_from_two_lines(resultt[1], resultt[2], "ProductType")	
	if value.to_i == 1
		return "Workstation"
	elsif value.to_i == 2
		return "Domain Controller"
	elseif value.to_i == 3
		return "Server"
	end
	return nil	
end

#get_wmi_system_type(login, password, host) ⇒ Object

return system type using a wmi request



83
84
85
86
# File 'lib/monitor/client/wmi/wmi.rb', line 83

def get_wmi_system_type(, password, host)
	resultt=wmi_request(, password, host, "select SystemType from Win32_ComputerSystem")
	return find_separated_value_from_two_lines(resultt[1], resultt[2], "SystemType")
end

#get_wmi_thermal_state(login, password, host) ⇒ Object

return the thermal state severity using a wmi request



44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/monitor/client/wmi/wmi.rb', line 44

def get_wmi_thermal_state(, password, host)
	resultt=wmi_request(, password, host, "select ThermalState from Win32_ComputerSystem")
	value=find_separated_value_from_two_lines(resultt[1], resultt[2], "ThermalState")
	if value.to_i == 1
		return "Other"
	elsif value.to_i == 3
		return "Safe"
	elsif value.to_i == 4
		return "Warning"
	elsif value.to_i == 5
		return "Critical"
	elsif value.to_i == 6
		return "Nonrecoverable"
	elsif value.to_i == 2
		return "Unkown"
	end
	return nil

#from http://msdn.microsoft.com/en-us/library/aa394102.aspx
#1 (0x1) Other
#2 (0x2) Unknown
#3 (0x3) Safe
#4 (0x4) Warning
#5 (0x5) Critical
#6 (0x6)Nonrecoverable

end

#getnetwork_and_mask(ip) ⇒ Object

return network address and compress mask class



699
700
701
702
703
704
# File 'lib/cmd_parse.rb', line 699

def getnetwork_and_mask(ip)
  if ip == "" || ip == nil
    return nil
  end
  return IPCalc.get_network_and_mask(ip)
end

#help_windowObject

provide help window



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/gui/help_window.rb', line 6

def help_window
  window = Gtk::Window.new
  window.set_size_request(500,300)
  window.set_title "Help"
  icon_name="#{PIXMAP_PATH}/logo_icon.png"
  Gtk::Window.set_default_icon(icon_name)
  window.show

  vbox = Gtk::VBox.new
  vbox.show
  window.add vbox

  text = Gtk::TextView.new
  text.cursor_visible=false
  text.set_size_request(350,300)
  text.set_editable(false)
  text.show

  scrolled_window = Gtk::ScrolledWindow.new(nil, nil)
  scrolled_window.border_width=2
  scrolled_window.set_policy(Gtk::POLICY_NEVER, Gtk::POLICY_ALWAYS)  

  vbox.pack_start(scrolled_window, true, true, 0)
  scrolled_window.show
  scrolled_window.add(text)

  text.grab_focus
  readme_file = "#{GNMSLIB}/../README"
  if FileTest.exist?(readme_file)
   fic = File.new(readme_file,'r')
   tlign = fic.readlines
   fic.close
   text.buffer.insert_at_cursor(tlign.join)
  else
    text.buffer.insert_at_cursor("Error: Could not find README file")
  end
  window.signal_connect("key_press_event") {|w,e|
	 if e.keyval == Gdk::Keyval::GDK_Escape
   	window.destroy
	 end
  }
end

#hexa_to_rgb_color(rgb) ⇒ Object

convert hexa value to a rgb Gdk::Color



63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# File 'lib/gui/color_macro.rb', line 63

def hexa_to_rgb_color(rgb)
	hexa_str=sprintf("%8x",rgb)
	tab=hexa_str.match(/(.{2})(.{2})(.{2}).{2}/)
	r=tab[1]
	g=tab[2]
	b=tab[3]
	
	if r== "  "
		r="00"
	elsif b=="  "
		b="00"
	end

	rd=sprintf("%d","0x#{r}")
	gd=sprintf("%d","0x#{g}")
	bd=sprintf("%d","0x#{b}")

	return Gdk::Color.new(rd.to_i()*256,gd.to_i()*256,bd.to_i()*256)
end

#hexa_to_rgb_color_str(rgb) ⇒ Object



83
84
85
86
87
88
89
90
91
92
# File 'lib/gui/color_macro.rb', line 83

def hexa_to_rgb_color_str(rgb)

  hexa_str=sprintf("%06x",rgb)
  hexa_str=hexa_str.chop()
  hexa_str=hexa_str.chop()
  if hexa_str.length < 6
    hexa_str="00"+hexa_str
  end
  return "##{hexa_str}"
end

#in_exception_list(str) ⇒ Object

check if node definition is matched by an entry from in_exception_list



112
113
114
115
116
117
118
119
# File 'lib/main.rb', line 112

def in_exception_list(str)
  $node_exception_list.each {|str_lign|
    if str_lign.match(str)
      return true
    end
    } unless $node_exception_list == nil
    return false
end

#init_level_alert_type(h) ⇒ Object

initialize level alert type corresponding to how alert is done according to the severity of the event



20
21
22
23
24
25
# File 'lib/gnms.rb', line 20

def init_level_alert_type(h)
	for l in $LEVEL
	  h[l]= [false,false,true,false,false,false,false,false] 
	end
	return 0
end

#insert_account_entry(node) ⇒ Object



71
72
73
74
75
76
77
78
79
80
81
# File 'lib/gui/sub/account_frame.rb', line 71

def (node)
	if !node.("default")
iter=@account_view.model.append
iter[0] = "default"
iter[1] = "value1"
iter[2] = "value2"
node.(iter[0], iter[1], iter[2])
	else
errorEntry(@window, "'default' account already exists")
	end
end

#invert_selected_nodeObject

invert node selection of the map



681
682
683
684
685
686
687
688
689
# File 'lib/main.rb', line 681

def invert_selected_node()
  $network[get_map()].get_node().each_value {|n|
    if n.node_view.selected?()
      n.node_view.unselect()
    else
      n.node_view.select()
    end
  }
end

#ip2netbiosname(ip) ⇒ Object

find netbios name



667
668
669
670
671
672
673
674
# File 'lib/cmd_parse.rb', line 667

def ip2netbiosname(ip)
  if $config.nmblookup_path == ""
    return nil
  end
  res=`#{$config.nmblookup_path} -A "#{ip}" | grep ACTIVE | awk '{print $1;}'`
  rest=res.split(/\n/)
  return rest[0] 
end

#jmx_request(host, port, user, pass, object_name, attr_names) ⇒ Object



495
496
497
498
# File 'lib/cmd_parse.rb', line 495

def jmx_request(host, port, user, pass, object_name, attr_names)
	rs=`#{GNMSLIB}/external/jjmx.rb #{host.ip} #{port} "#{user}" "#{pass}" #{$jmx_refs[object_name].mbean} "#{attr_names}" 2>&1`
	return rs.split(/\n/)
end

#launch_gnms_mainObject

main



936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
# File 'lib/main.rb', line 936

def launch_gnms_main()

  #  begin

  Thread.abort_on_exception = true

  $config=ConfigGlobal.new()
  #read config
  $config.read_config_yaml()
  
  #set saved log level
  $log.level = txtlvl_to_loggerlvl($config.log_level)

  #verify nmap version
  check_scanner_version()

  #create host hash
  $host=Hash.new

  #create network hash
  $network=Hash.new

  #create link hash for global operation
  $links=[]

  #oid ref for snmp monitoring
  $oid_refs=Hash.new
  #wmi ref for wmi monitoring
  $wmi_refs=Hash.new
  #syslog ref for syslog monitoring
  $syslog_refs=Hash.new
  #snmptrap ref for snmptrap monitoring
  $snmptrap_refs=Hash.new
  #http ref for http monitoring
  $http_refs=Hash.new
  #jmx ref for jmx monitoring
  $jmx_refs=Hash.new

  #create contacts
  $contact=Hash.new

  Syslog.open(PROJECTNAME, Syslog::LOG_PID | Syslog::LOG_NDELAY)

  #load some hidden window in background
  $treenode_win=TreeNodeWindow.new
  $event_win=EventWindow.new

  #by default first map is root map
  $map=nil
  map_window()

  #we have loaded all node
  $event_win.update_statusbar()
  $treenode_win.reload()
  thread_starting()

  interfaces_table = local_interface()
  if interfaces_table.size > 0
    ip_of_first_interface = interfaces_table[0][0]
    $event_win.add_event(EventWindow::CORE_EVENT_TYPE,"INFO",$host[ip_of_first_interface], "GNMS launch")
  else
    $event_win.add_event(EventWindow::CORE_EVENT_TYPE,"INFO",$host["127.0.0.1"], "GNMS launch")
  end

  #node we don't want to see
  $node_exception_list = Array.new
  
  #rescue Exception => msg
  #	puts "-"*80
  #	$log.fatal("Please report this error: #{msg}\n#{msg.backtrace.join("\n")}")
  #	puts "-"*80
  #  end
end

#layout_grid(map) ⇒ Object

try to display node of map arg as a grid need: an ip addr map



382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
# File 'lib/main.rb', line 382

def layout_grid(map)
  if map != nil

    root_width=$win.window.geometry[2]
    root_height=$win.window.geometry[3]
    x=0
    y=0

    $network[map].get_node().each_value {|node|
      node_v = node.node_view
      if node_v
        node_size=node_v.get_node_size()
        node_v.move(x-node.x, y-node.y)
        x+=node_size+root_width/node_size
        if x >= root_width
          x=0
          y+=node_size+node_size/2+root_height/node_size
        end
        if node.nb_links > 0
          node.get_links().each {|lnk|
            lnk.remove_link
            lnk.display()
          }
        end
      end
    }
  end
end

#listport(ip) ⇒ Object

list port with nmap



146
147
148
149
150
151
152
153
154
155
156
157
158
# File 'lib/cmd_parse.rb', line 146

def listport(ip)
    lp=""
    nmap_version = $config.nmap_vers.to_f()
    if nmap_version >= 6.0 
      lp=`#{$config.nmap_path} -sU -sT #{ip} --host_timeout 60 2>/dev/null| grep open | grep "^[0-9]"`
    else
      if nmap_version > 0.0
        lp=`#{$config.nmap_path} -sU -sT #{ip} --host_timeout 60000 2>/dev/null| grep open | grep "^[0-9]"`
      end
    end
    result = lp.gsub("/"," ").gsub("open","").gsub("|filtered","").gsub("\ +"," ")    
    return result
end

#load_image(file, keepisgeometry = "") ⇒ Object

load image, return a pixmap



9
10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/gui/color_macro.rb', line 9

def load_image (file, keepisgeometry="")
  if file[0,1] == '/'
    rfile = file
  else
    rfile = "#{PIXMAP_PATH}/#{file}"
  end
  if FileTest.exist? rfile
    im = Gtk::Image.new(rfile)
  else
    print "#{rfile} doesnt exist!","\n"
    load_image "type/pc.gif"
  end
end

#local_interfaceObject

Return interface info of local machine

format is an array of array of elements
ipv4 mask ipv6 mac_addr interface_name


193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
# File 'lib/cmd_parse.rb', line 193

def local_interface()	
   result = Array.new
   Facter::Util::IP.get_interfaces.each do |interface|
      tmp= Array.new
	%w{ipaddress netmask ipaddress6 macaddress}.each do |label|
              tmp.push Facter::Util::IP.get_interface_value(interface, label)
	  end
	  #tmp.push interface
	  #check if ip is not empty
      if !tmp[0].nil? and !tmp[0].empty?
        result.push tmp
      end      
   end
   return result
end

#local_maskObject

Return netmask adress of local machine



212
213
214
215
216
217
# File 'lib/cmd_parse.rb', line 212

def local_mask()
   Facter::Util::IP.get_interfaces.each do |interface|     
              return Facter::Util::IP.get_interface_value(interface, "netmask") if interface != "lo"
   end
   return nil
end

#mac(ip) ⇒ Object

Return the MAC address of the ip give in argument, use snmp



165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
# File 'lib/monitor/client/snmp/snmp.rb', line 165

def mac(ip)
  #first try to solve it by the help of local arp table
  temp=mac_tablelocal(ip)

  if (temp!="")
    return temp.chomp
  end
  if !$config.snmp_mon || $host[ip].status == CRITICAL
      return
  end
  val=get_snmp_OID($host[ip], "ipAdEntIfIndex.#{ip}")
	if !val || val == "Error"
    return
  end
  result=get_snmp_OID($host[ip], "ifPhysAddress.#{val}")
  #expecting the MAC address as a string
  if !result.ascii_only?
    #if binary, we tried to convert it
    result = result.unpack("H2H2H2H2H2H2").join(":")
  end

  if !isValidMac(result)
    return
  end
  return result
end

#mac_manufacturer_list_exist?Boolean

return if mac manufacturer list exist

Returns:

  • (Boolean)


104
105
106
# File 'lib/cmd_parse.rb', line 104

def mac_manufacturer_list_exist?()
	return FileTest.exist?("#{CONF_DIR}/oui.txt")
end

#mac_tablelocal(ip) ⇒ Object

Return mac adress of the ip if in local arp table



179
180
181
182
183
184
185
186
187
# File 'lib/cmd_parse.rb', line 179

def mac_tablelocal(ip)
        `ping -c 1 -W 1 #{ip}`
	lp=`arp -n #{ip} | grep #{ip} | awk '{print $3;}'`
	#there is no entry
	if lp.chomp == "--"
	  lp=""
	end
	return lp
end

#map_windowObject

create main network map window



730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
# File 'lib/main.rb', line 730

def map_window()
  nbuttons = n_host()

  begin
    #it depends on gnome version
    $icon = Gtk::StatusIcon.new
    $icon.set_pixbuf(Gdk::Pixbuf.new("#{PIXMAP_PATH}/logo_icon.png"))
    $icon.signal_connect('activate') { switch_main_visibility }
  rescue
    $icon=nil
  end

  $win = App.new("Map")
  $win.set_default_size(get_default_map_width(), get_default_map_height())
  $win.resize(get_default_map_width(), get_default_map_height())

  #here we set the background color
  window_set_rgb($config.rgb[0].to_f, $config.rgb[1].to_f, $config.rgb[2].to_f)
  $win.signal_connect("delete_event") {
    $root_width=$win.window.geometry[2]
    $root_height=$win.window.geometry[3]

    #check if the current windowmanager display the trayicon
    if $icon && $icon.embedded?
      #if it's the case we just hide the main window
      $win.hide
    else
      confirm_exit_window()
    end
  }

  $win.signal_connect("destroy") {
  }
  
  $win.signal_connect("configure_event") {|w,e|
    #size or position changed
    if $win != nil
      if (($root_width != e.width) or ($root_height != e.height))
        if (!$win.get_size_changed_from_menu())
          $win.set_display_view_menu()
        end
        $win.set_size_changed_from_menu(false)
      end
    end
  }

  #read command line options
  file_to_load=nil
  debuglevel=nil
  $testunit=false
  testunitfile=nil

  opts = OptionParser.new
  opts.on("-f=ARG", "--file filename",String,"Load xml node filename") {|val| file_to_load=val }
  opts.on("-d=ARG", "--debug level",Integer,"Set debug output level (0 is the most verbose)") {|val| debuglevel=val }
  opts.on("-t=ARG", "--test scenario",String,"Load and execute scenario from test/ dir") {|val| testunitfile=val
    $testunit=true
  }
  opts.on("-h", "--help","Show this help") {|val| puts opts.to_s; exit}
  opts.on("-v", "--version","Display GNMS version") {|val| puts "GNMS version is #{GNMSVERSION}"; exit}

  begin
    opts.parse(ARGV)
  rescue OptionParser::MissingArgument => msg
  rescue OptionParser::InvalidOption => msg
  rescue OptionParser::InvalidArgument => msg
    $log.error("#{msg}")
    exit
  end

  if (debuglevel != nil) && (debuglevel >= 0) && (debuglevel < 5)
    $log.level=debuglevel
  end

  if testunitfile == nil
    if file_to_load != nil
      if FileTest.exist?(file_to_load)
        $log.info("Loading nodes from file #{file_to_load}")
        read_xml(file_to_load)
      else
        $log.error("#{file_to_load} is not an host db file")
        exit
      end
    else
      if FileTest.exist?(SQLITE_DB)
        $log.info("Loading nodes from database")
        db_read()
        #we have to verify if account from conf file and from db matched
        $config.mail_by_level=check_contact_value($config.mail_by_level)
        $config.sms_num_by_level=check_contact_value($config.sms_num_by_level)
        $config.im_dest_by_level=check_contact_value($config.im_dest_by_level)
      else
        create_db()
        #as we don't have account in db we will assure no account come from conf file
        $config.init_hash_conf_by_level($config.mail_by_level)
        $config.init_hash_conf_by_level($config.sms_num_by_level)
        $config.init_hash_conf_by_level($config.im_dest_by_level)

        if n_host() == 0
          $log.info("Creating default node based on local interfaces")
          create_root_network()
          for interface in local_interface()
            #syntax array of [ipv4 mask ipv6 mac_addr interface_name]
		(ipv4, mask, ipv6, mac_addr, interface_name) = interface
		if !exist_host(ipv4)
              if add_host(ipv4, IPCalc.netmask_to_bits(mask))
   if mac_addr
      $host[ipv4].mac = mac_addr
   end
   if interface_name
      $host[ipv4].add_interface(interface_name)
   end
   #then try to add naming info and os
   tmp = Facter::hostname
   if tmp
     #special case
     if ipv4 == "127.0.0.1"
        tmp="localhost"
     end
     $host[ipv4].name = tmp
   end
   tmp = nil
   tmp = Facter::domain
   if tmp
     $host[ipv4].dns_domain = tmp		       
   end
   tmp = nil
   tmp = Facter::fqdn
   if tmp
     $host[ipv4].dns_name = tmp		       
   end
   tmp = nil
   tmp = Facter::kernel
   if tmp
     $host[ipv4].os = tmp.downcase
   end
                 tmp = nil		     
end
            end
          end
        end
      end
    end
    #set current map
    map_tmp=nil
    if $config.default_map != ""
      if exist_network($config.default_map)
        map_tmp=$config.default_map
      end
    end
    #here we also set the pixmap background
    set_map(map_tmp)
  else
    #execute the test unit script
    $log.info("Running test scenario #{TEST_DIR}/#{testunitfile}")
    File.delete(SQLITE_DB_TEST) unless !FileTest.exist?(SQLITE_DB_TEST)
    File.delete(GLOBAL_CONF_TEST_FILE) unless !FileTest.exist?(GLOBAL_CONF_TEST_FILE)
    create_db(SQLITE_DB_TEST)
    #as we don't have account in db we will assure no account come from conf file
    $config.init_hash_conf_by_level($config.mail_by_level)
    $config.init_hash_conf_by_level($config.sms_num_by_level)
    $config.init_hash_conf_by_level($config.im_dest_by_level)
    create_root_network()

    begin
      require "#{TEST_DIR}/#{testunitfile}"
      cmd="#{testunitfile[0,1].capitalize()}#{testunitfile[1,testunitfile.size - 1]}"
      (eval cmd).new
    rescue Exception => msg
      print #{msg.backtrace.join("\n")},"\n"
      $log.fatal("Test scenario #{TEST_DIR}/#{testunitfile}.rb does not exist")
      exit()
    end
  end

  #hide splash_screen
  #splash_screen.hide
  #splash_screen.destroy

  $win.set_icon_name("MAP")
  $win.set_icon("#{PIXMAP_PATH}/logo_icon.png")
  $win.show
  $root_width, $root_height=$win.size

  if ! FileTest.exist?(GLOBAL_CONF_FILE)
    $config.show()
  end

end

#n_hostObject

return the number of host



414
415
416
# File 'lib/main.rb', line 414

def n_host()
  return $host.size
end

#n_networkObject

return the number of network



421
422
423
# File 'lib/main.rb', line 421

def n_network()
  return $network.size
end

#nb_lign_db(fic = DEFAULTHOSTDB) ⇒ Object

return nb lign of the file db



1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
# File 'lib/node_db.rb', line 1853

def nb_lign_db(fic=DEFAULTHOSTDB)
	if FileTest.exist?(fic)
		fic = File.new(fic,'r')
		lign=fic.gets
		nblign=1
		while lign
			lign=fic.gets
			nblign+=1
		end
		fic.close
	end
	return nblign
end

#net2bitmask(netmask) ⇒ Object

convert netmask address to bitmask address



689
690
691
692
693
694
# File 'lib/cmd_parse.rb', line 689

def net2bitmask(netmask)
  if netmask =="0.0.0.0"
    return 0
  end
  return IPCalc.netmask_to_bits(netmask)
end

#netmask_calculatorObject

window to get info from ip/mask



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
# File 'lib/gui/ipcalculator.rb', line 6

def netmask_calculator

    if $win == nil
  	    return
    end

    ipcalc=Gtk::Window.new

    ipcalc.set_title("IP calculator")
    ipcalc.set_size_request(340, 340)
    ipcalc.set_modal(true)

    ipcalc.signal_connect("key_press_event") {|w,e|
      if e.keyval == Gdk::Keyval::GDK_Escape
        ipcalc.destroy
      end
    }

    vbox = Gtk::VBox.new
    vbox.show
    ipcalc.add vbox

	 frame=Gtk::Frame.new
	 frame.border_width=10
	 frame.show
	 vbox.add frame

    table = Gtk::Table.new(3,2,false)
    table.show

    label_ip = Gtk::Label.new "IP"
    label_ip.show
    entry_ip = Gtk::Entry.new
    entry_ip.set_text "0.0.0.0"
    entry_ip.show
    eval_button = Gtk::Button.new(Gtk::Stock::EXECUTE)
    eval_button.show

    hbox = Gtk::HBox.new
    hbox.show

	 hbox.add entry_ip
	 hbox.add eval_button

    table.attach(label_ip,0,1,0,1)
    table.attach(hbox,1,2,0,1)

    label_netmask = Gtk::Label.new "Netmask"
    label_netmask.show
	
    hbox = Gtk::HBox.new
    hbox.show
    entry_netmask = Gtk::Entry.new
    entry_netmask.set_text DEFAULT_CLASS_C_NETMASK
    entry_netmask.set_editable false
    entry_netmask.show
  
    adj = Gtk::Adjustment::new(0, 1.0, 32.0, 1.0, 5.0, 0.0)
    compressnetmask = Gtk::SpinButton::new(adj, 0, 0)
    compressnetmask.set_wrap(true)
    compressnetmask.set_editable false
    compressnetmask.set_value 24.0

    compressnetmask.show
    hbox.add entry_netmask
    hbox.add compressnetmask
    table.attach(label_netmask,0,1,1,2)
    table.attach(hbox,1,2,1,2)
    text = Gtk::TextView.new
    text.cursor_visible=false
    text.set_size_request(150,200)
    text.set_editable(false)
    text.show
    
    bbox = Gtk::HButtonBox.new
    bbox.set_layout_style(Gtk::ButtonBox::SPREAD)
    bbox.set_size_request(50,30)
    bbox.show

    compressnetmask.signal_connect("value-changed") {
      entry_netmask.set_text bit2netmask(compressnetmask.value_as_int)
    }

    eval_button.signal_connect("clicked") {
    if isValidIPv4(entry_ip.text)
   	text.buffer.place_cursor(text.buffer.start_iter)
   	if compressnetmask.value == "0"
        text.buffer.insert_at_cursor(IPCalc::ipcalc_detail(entry_ip.text))
   	else
        text.buffer.insert_at_cursor(IPCalc::ipcalc_detail("#{entry_ip.text}/#{compressnetmask.text}"))
   	end
    else 
    	errorEntry(ipcalc, entry_ip.text)
    end
    }
    entry_ip.signal_connect("key_press_event") {|w,e|
      if e.keyval == 65293 || e.keyval == 65421 #Enter key
        eval_button.clicked
      end
    }
    entry_netmask.signal_connect("key_press_event") {|w,e|
      if e.keyval == 65293 || e.keyval == 65421 #Enter key
        eval_button.clicked
      end
    }
    compressnetmask.signal_connect("key_press_event") {|w,e|
      if e.keyval == 65293 || e.keyval == 65421 #Enter key
        eval_button.clicked
      end
    }
    
    
  clear_button = Gtk::Button.new(Gtk::Stock::CLEAR)
  clear_button.show
  clear_button.signal_connect("clicked") {
	  text.buffer.delete(text.buffer.start_iter,text.buffer.end_iter)
  }

  cancel_button = Gtk::Button.new(Gtk::Stock::CLOSE)
  cancel_button.show
  cancel_button.signal_connect("clicked") {
  	  ipcalc.destroy 
  }

  bbox.add clear_button
  bbox.add cancel_button
  frame.add table
	
  scrolled_window = Gtk::ScrolledWindow.new(nil, nil)
  scrolled_window.border_width=2
  scrolled_window.set_policy(Gtk::POLICY_NEVER, Gtk::POLICY_AUTOMATIC)  

  vbox.add scrolled_window
  scrolled_window.show
  scrolled_window.add(text)

  separator = Gtk::HSeparator::new()
  separator.show
  vbox.add separator
  vbox.add bbox
  ipcalc.show
end

#network_status_pie(node, size = 400) ⇒ Object

this file contains all method to drawing charts



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/gui/charts/gruff.rb', line 5

def network_status_pie(node, size=400)

  g=Gruff::Pie.new(size)
	begin
		#this method depends on gruff version
  		g.legend_at_bottom=true
	rescue
	end

  g.theme = {
    :marker_color => 'black',
    :font_color => 'black',
    :background_colors => 'transparent'
  }

  sev_stat=Array.new($status_value.size,0)

  node.get_node().each_value do |n| 
		sev_stat[$status_value.index(n.status)]+=1
  end

  status_index=0
  $status.each do |stat|

	 sev_percent=0
	 if node.nb_node>0
		sev_percent=(sev_stat[status_index]*100)/node.nb_node.to_f()
	 end
	 if sev_stat[status_index] > 0
		  g.data(sev_stat[status_index].to_s()+" "+stat.capitalize(), [sev_percent.round()], hexa_to_rgb_color_str($status_color[status_index]))
	 end
	 status_index+=1
end

#g.hide_legend=true
#g.data("Critical", [1])
#g.data("Major", [1])
#g.data("Warning", [1])
#g.data("Minor", [1])
#g.data("Normal", [1])
#g.data("Unmanaged", [1])
#g.data("Unkown", [1])

#g.write('my_test.png')
return g.to_blob { self.format='PNG' }

end

#network_to_xml(ip) ⇒ Object



2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
# File 'lib/node_db.rb', line 2354

def network_to_xml(ip)
  doc = Document.new
  doc.add_element("Network")

  i=1
  doc.root.add_element("uuid")
  doc.root.elements[i].text = $network[ip].uuid
  i+=1
  doc.root.add_element("ip")
  doc.root.elements[i].text = $network[ip].ip
  i+=1
  doc.root.add_element("mask")
  doc.root.elements[i].text = $network[ip].netmask
  i+=1
  doc.root.add_element("map")
  doc.root.elements[i].text = $network[ip].map
  i+=1
  doc.root.add_element("services")
  services=doc.root.elements[i]
  $network[ip].service.each_value {|serv|
    service=Element.new("service")
    service.add_element("protocol")
    service.elements["protocol"].text = serv.protocol
    service.add_element("port")
    service.elements["port"].text = serv.port
    service.add_element("name")
    service.elements["name"].text = serv.name
    service.add_element("monitor")
    service.elements["monitor"].text = serv.monitor
    services.elements << service
  }
  i+=1

  doc.root.add_element("status")
  doc.root.elements[i].text = $network[ip].status
  i+=1

  doc.root.add_element("x")
  doc.root.elements[i].text = $network[ip].x
  i+=1

  doc.root.add_element("y")
  doc.root.elements[i].text = $network[ip].y
  i+=1

  doc.root.add_element("icon")
  doc.root.elements[i].text = $network[ip].icon
  i+=1

  doc.root.add_element("description")
  doc.root.elements[i].text = $network[ip].description
  i+=1

  doc.root.add_element("snmp_version")
  doc.root.elements[i].text = $network[ip].snmp_version
  i+=1

  doc.root.add_element("snmp_port")
  doc.root.elements[i].text = $network[ip].snmp_port
  i+=1

  doc.root.add_element("snmp_port")
  doc.root.elements[i].text = $network[ip].snmp_port
  i+=1

  doc.root.add_element("snmp_retry")
  doc.root.elements[i].text = $network[ip].snmp_retry
  i+=1

  doc.root.add_element("type")
  doc.root.elements[i].text = $network[ip].type
  i+=1

  doc.root.add_element("os")
  doc.root.elements[i].text = $network[ip].os
  i+=1

  doc.root.add_element("name")
  doc.root.elements[i].text = $network[ip].name
  i+=1

  doc.root.add_element("dns_domain")
  doc.root.elements[i].text = $network[ip].dns_domain
  i+=1

  doc.root.add_element("netbios_domain")
  doc.root.elements[i].text = $network[ip].netbios_domain
  i+=1

  doc.root.add_element("node_size")
  doc.root.elements[i].text = $network[ip].node_size
  i+=1

  doc.root.add_element("map_bg_type")
  doc.root.elements[i].text = $network[ip].map_bg_type
  i+=1

  doc.root.add_element("map_bg_data")
  if $network[ip].map_bg_type == "color"
    doc.root.elements[i].text = $network[ip].map_bg_data.join(" ")
  else
    doc.root.elements[i].text = $network[ip].map_bg_data
  end
  i+=1

  doc.root.add_element("inherit_from_global")
  doc.root.elements[i].text = b2i($network[ip].inherit_from_global)
  i+=1

  return doc
end

#nmap_versionObject

get nmap version



163
164
165
166
167
168
169
170
171
172
173
174
# File 'lib/cmd_parse.rb', line 163

def nmap_version()
	if $config.nmap_path != ""
		regx=Regexp.new('Nmap version ([\d.]+) \(')
		if $config.nmap_path
			ret=`#{$config.nmap_path} -V|grep Nmap`
			ret.scan(regx) do |val|
				return val[0]
			end
		end
		return nil
	end
end

#node_property(node) ⇒ Object



30
31
32
33
34
35
36
37
38
39
# File 'lib/node_property.rb', line 30

def node_property(node)
  if node.status == UNMANAGED
    return
  end
  if node.class == Host
	  NodeHostProperty.new(node)
  else
	  NodeNetworkProperty.new(node)
  end
end

#open_db(fic = SQLITE_DB) ⇒ Object

open sqlite database, assign $db global variable



23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/node_db.rb', line 23

def open_db(fic=SQLITE_DB)
	if FileTest.exist?(fic) and (!File.readable?(fic) or !File.writable?(fic))
	      $log.fatal("Wrong permission on  #{fic} need read-write access")
	      exit()
        end
	begin
		$db = SQLite3::Database.new(fic)
		$db.default_synchronous = 'off'
		$db.synchronous = 'off'
	rescue
		$log.fatal("#{fic} database corrupted")
		exit()
	end
end

#osfingerprint(ip) ⇒ Object

OS Fingerprint



600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
# File 'lib/cmd_parse.rb', line 600

def osfingerprint(ip)

  $log.debug "cmd_parse osfingerprint #{ip}"

  if $config.xprobe_path != ""
    #with xprobe version 1
    #res=`#{$config.xprobe_path} #{ip} 2>&1 | grep "FINAL"`
    #with xprobe version 2
    res=`#{$config.xprobe_path} -c /etc/xprobe2/xprobe2.conf -m 1 #{ip} 2>&1 | grep "Running OS"`
	# seems xprobe2 get a segfault when he can't find the interface to contact the ip

	if (res == "")
            nmap_version = $config.nmap_vers.to_f()
            if nmap_version >= 6.0 
	       res=`#{$config.nmap_path} -O #{ip} --host_timeout 10 2>&1 | grep "Running: "`
	    else
	       res=`#{$config.nmap_path} -O #{ip} --host_timeout 10000 2>&1 | grep "Running: "`		
	    end
	end

    if (res!="")
    if (res.index("Linux")!=nil)
  	  res="linux"
      return res
    end
  	if (res.index("Win")!=nil)
  	  res="windows"
      return res
	end
    if (res.index("HPUX")!=nil)
  	  res="hp"
      return res
    end
    if (res.index("3Com")!=nil)
      res="3com"
      $host[ip].type="switch"
      return res
    end
    if (res.index("Cisco")!=nil)
      res="cisco"
      $host[ip].type="router"
      return res
    end
    if (res.index("BSD")!=nil)
      res="freebsd"
      return res
    end    
    end
  end
  return ""
end

#ping(ip) ⇒ Object

To know if an host is up, we use here ping perhaps in a near future nmap



232
233
234
235
# File 'lib/cmd_parse.rb', line 232

def ping (ip)
	pip=`#{$config.ping_path} #{ip} -c 1 -n -W 4 2>/dev/null | grep ^64`
	return pip!=""
end

#portscan_node(n) ⇒ Object

scan a given node trying to reach following services: ftp, ssh, http(s), dns, smtp, pop3, imap, nntp, ldap(s), kerberos, rdp



894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
# File 'lib/node_listener.rb', line 894

def portscan_node(n)

  tcp_service_to_check = [21, 22, 80, 25, 110, 143, 119, 389, 443, 636, 3389]
  udp_service_to_check = [53]
  
  udp_service_to_check.each {|port|
    p1 = Net::Ping::UDP.new(n.ip, port)
    if p1.ping?
      return 1
    end
  }
  
  tcp_service_to_check.each {|port|
    p1 = Net::Ping::TCP.new(n.ip, port)
    if p1.ping?
      return 1
    end
  }
  return 0  
end

#quit_allObject



1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
# File 'lib/main.rb', line 1144

def quit_all
  $config.write_config_yaml()
  #kill threads
  thread_stopping()
  #stop event thread
  $event_win.stop_analyzer()
  #we need to save the nodes in db
  save_all_in_db()
  sleep(1) until !$win.busy?     
  
  if File.exists?(PID_FILE)
     begin
        File.delete(PID_FILE)
	 rescue Exception => msg
 $log.error(msg)
	 end
  end
  Syslog.close if Syslog
  $win.destroy
  Gtk.main_quit
end

#quit_nowObject



1094
1095
1096
1097
1098
# File 'lib/main.rb', line 1094

def quit_now()
  if !confirm_exit_window()
    quit_all()
  end
end

#range_remote_ping(ip_begin, ip_end) ⇒ Object

Return all host seems to be up (responding to icmp) from a given range IP addr



577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
# File 'lib/cmd_parse.rb', line 577

def range_remote_ping(ip_begin, ip_end)
  #puts "in range_remote_ping"
  result=[]
  if $config.nmap_path == ""
    return result
  end
  res=nil
  if $config.nmap_vers.to_f() >= 4
	  res=`#{$config.nmap_path} --send-ip -sP -n "#{ip_begin}-#{ip_end}" 2>/dev/null| grep "^H.*$" | awk '{print $2}'`
  else
	  res=`#{$config.nmap_path} -sP -n "#{ip_begin}-#{ip_end}" 2>/dev/null| grep "^H.*$" | awk '{print $2}'`	
  end

  lres=res.split(/\n/)
  for ip in lres
    result.push ip
  end
  return result
end

#read_xml(fic = DEFAULTHOSTDB) ⇒ Object



2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
# File 'lib/node_db.rb', line 2330

def read_xml(fic=DEFAULTHOSTDB)
  set_busy()
  #we do not check here if the xml file is valid
  $log.info("Loading nodes")
  listener = Listener.new
  begin
    file=File.new(fic)
  rescue
    $log.error("File #{fic} not found")
    create_root_network()
    return
  end
  parser = Parsers::StreamParser.new(file, listener)
  parser.parse()
  $log.info("Node database rebuilt")
  #here we assume we have loaded all networks
  #we update network host list where in fact host is a network in network
  $network.each_key {|ip|
     host=$network[ip]
     $network[host.map].add_network(host) unless host.map == nil
  }
  set_unbusy()
end

#remove_selected_account_entry(node) ⇒ Object



83
84
85
86
87
88
89
90
91
92
# File 'lib/gui/sub/account_frame.rb', line 83

def (node)
	if @account_view.selection.selected
if (node.ip != ROOTMAPADDR) && (@account_view.model.get_value(@account_view.selection.selected,0)!= "snmp")
    node.(@account_view.model.get_value(@account_view.selection.selected,0))
    @account_view.model.remove(@account_view.selection.selected)
else
	errorEntry(@window, "'snmp' account can't be deleted")
end
	end
end

#rgb_to_hex_color(rgb) ⇒ Object

convert rgb to hex color str



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/gui/color_macro.rb', line 41

def rgb_to_hex_color(rgb)
	if rgb.class == Gdk::Color
		r,g,b=rgb.to_a()
		r=(r-1)/256 unless r==0
		g=(g-1)/256 unless g==0
		b=(b-1)/256 unless b==0
		hex_result=""
		[r,g,b].each do |comp|
				hex=sprintf("%x",comp)
				if hex == '0'
					hex_result+="00"
				else
					hex_result+=hex
				end
		end
		return hex_result
	end
end

#save_all_in_dbObject

call all db method to save all the map in the db



1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
# File 'lib/main.rb', line 1103

def save_all_in_db()
   $log.info("Saving nodes")
   #save nodes
   set_busy()

   Thread.start {
	  $host.each_key {|ip|
        $log.debug("Saving node host #{ip}")
        nodeid=db_get_node_id(ip, HOSTNODE)
 db_set_mac(nodeid, $host[ip].mac)
        db_set_node_type_and_os(nodeid, $host[ip].type, $host[ip].os)
        db_set_node_position(nodeid, $host[ip].x, $host[ip].y)
        db_set_severity(nodeid, $host[ip].status, $host[ip].avail_sev, $host[ip].snmp_sev, $host[ip].custom_sev,$host[ip].trap_sev,$host[ip].service_sev,$host[ip].wmi_sev,$host[ip].syslog_sev,$host[ip].jmx_sev)
        db_set_map(nodeid, $host[ip].map)
        db_set_name(nodeid, $host[ip].name, $host[ip].dns_name, $host[ip].dns_domain, $host[ip].netbios_name, $host[ip].netbios_domain)
 db_set_interfaces(ip, $host[ip].interface)
	  }

	  $network.each_key {|ip|
        $log.debug("Saving node network #{ip}")
        nodeid=db_get_node_id(ip,NETWORKNODE)
        db_set_node_type_and_os(nodeid, $network[ip].type, $network[ip].os)
        db_set_node_position(nodeid, $network[ip].x, $network[ip].y)
        db_set_severity(nodeid, $network[ip].status, $network[ip].avail_sev, $network[ip].snmp_sev, $network[ip].custom_sev, $network[ip].trap_sev,$network[ip].service_sev,$network[ip].wmi_sev,$network[ip].syslog_sev,$network[ip].jmx_sev)
        db_set_map(nodeid, $network[ip].map)
        db_set_name(nodeid, $network[ip].name, Node::NONAME_PROPERTY, $network[ip].dns_domain, Node::NONAME_PROPERTY, $network[ip].netbios_domain)
        db_set_node_size(nodeid, $network[ip].node_size)
        if ip == ROOTMAPADDR
          #make sure latest snmp read/write community have been stored
          (nodeid, "snmp", $config.read_community, $config.write_community)
        end
	  }

	  #save links
	  db_del_links()
	  db_set_links()
	  #unset cursor
	  set_unbusy()      
   }      
end

#scan_port(ip, proto, port) ⇒ Object

scan a given ip, proto/port return 1 when the service is responding or 0



874
875
876
877
878
879
880
881
882
883
884
885
886
# File 'lib/node_listener.rb', line 874

def scan_port(ip, proto, port)
  p1 = nil
  protocol = proto.upcase
  if protocol == "UDP"
    p1 = Net::Ping::UDP.new(ip, port)
  elsif protocol == "TCP"  
    p1 = Net::Ping::TCP.new(ip, port)
  end
  if !p1.nil? and p1.ping?
    return 1
  end
  return 0
end

#select_all_nodeObject

select all node of the map



672
673
674
675
676
# File 'lib/main.rb', line 672

def select_all_node()
  $network[get_map()].get_node().each_value {|n|
    n.node_view.select()
  }
end

#service_name(protocol, port) ⇒ Object

Return the service name associate to the port given in argument first is protocol, second is port



655
656
657
658
659
660
661
662
# File 'lib/cmd_parse.rb', line 655

def service_name(protocol, port)
  serv = ""
  begin
    serv = Socket.getservbyport(port.to_i, protocol)
  rescue
  end
  return serv
end

#set_background_color(rgb) ⇒ Object

set map window background color



660
661
662
663
664
665
666
667
# File 'lib/main.rb', line 660

def set_background_color(rgb)
  r,g,b=rgb.to_a()
  r=r.to_f
  g=g.to_f
  b=b.to_f
  window_set_rgb(r, g, b) unless $win == nil
  $canvas.set_rgb(r, g, b) unless $canvas == nil
end

#set_busyObject



1086
1087
1088
# File 'lib/main.rb', line 1086

def set_busy()
   $win.busy()
end

#set_map(mp = nil) ⇒ Object

set current map by is IP addr



546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
# File 'lib/main.rb', line 546

def set_map(mp=nil)

$canvas.get_selected_node().each {|n|
  n.node_view.unselect()
  } unless $canvas == nil
  #first set map
  if $map == nil && mp ==nil && $network[ROOTMAPADDR]
    #puts "1"
    $network[ROOTMAPADDR].node_view.show()
    $network[ROOTMAPADDR].map_view.visibility = Goo::CanvasItem::INVISIBLE
  else
    if $map == nil && $network[ROOTMAPADDR]
      #puts "2"
      #only the network root can have a nil map
      $network[ROOTMAPADDR].get_node().each_value {|node|
        node.node_view.hide_text() unless !node.node_view
      }
      $network[ROOTMAPADDR].node_view.hide()
    else
      if $network[ROOTMAPADDR]
         $network[$map].get_node().each_value {|node|
           node.node_view.hide_text() unless !node.node_view
         }
         $network[$map].map_view.visibility = Goo::CanvasItem::INVISIBLE
	end
    end
    if mp == nil && $network[ROOTMAPADDR]
      #puts "4"
      #only the network root can have a nil map
      $network[ROOTMAPADDR].node_view.resize()
      $network[ROOTMAPADDR].reload()
      if $network[ROOTMAPADDR].set_label_visibility()
        $network[ROOTMAPADDR].change_label($config.network_label_view)
        $network[ROOTMAPADDR].node_view.show_text()
      else
        $network[ROOTMAPADDR].node_view.hide_text()
      end
      $network[ROOTMAPADDR].node_view.show()
      if $config.bg_type == "color"
        $canvas.unset_background_image()
        set_background_color($config.rgb)
      else
        $canvas.set_background_image("#{PIXMAP_PATH}"+"/"+$config.image_path)
      end
      $win.hide_menu_entry()
    else
      #for each node of the new map, we refresh size icon, icon type and label type
      tmp_node=$network[mp]
      if tmp_node
        tmp_node.get_node().each_value {|n|
          n.node_view.resize() unless !n.node_view
          #n.reload()
          if n.set_label_visibility()
            if n.class == Network
              n.change_label($config.network_label_view)
            elsif n.class == Host
              n.change_label($config.host_label_view)
              n.refresh_dns_name()
            end
            n.node_view.show_text() unless !n.node_view
          else
            n.node_view.hide_text() unless !n.node_view
          end
          #show the node icon view
          n.node_view.show() unless !n.node_view
        }

        $network[mp].map_view.visibility = Goo::CanvasItem::VISIBLE

        #test $map and mp bg_type ?
        #puts $network[mp].map_bg_type
        if ($network[mp].map_bg_type != nil)
          if $network[mp].map_bg_type == "color"
            if ($network[mp].map_bg_data != $config.rgb) || ($config.bg_type == "image")
              $canvas.unset_background_image()
              set_background_color($network[mp].map_bg_data)
            end
          else
            if ($config.bg_type!=$network[mp].map_bg_type) || ( ($config.bg_type==$network[mp].map_bg_type) && ($network[mp].map_bg_data != $config.image_path))
              $canvas.set_background_image("#{PIXMAP_PATH}"+"/"+$network[mp].map_bg_data)
            end
          end
        else
          if $config.bg_type == "color"
            $canvas.unset_background_image()
            set_background_color($config.rgb)
          else
            if (!$canvas.background_image_isset?()) || ($network[mp].map_bg_data != $config.image_path)
              $canvas.set_background_image("#{PIXMAP_PATH}"+"/"+$config.image_path)
            end
          end
        end
        $win.show_menu_entry()
      end
    end
    $map=mp
    set_map_window_title(mp)
  end
end

#set_map_window_title(mp) ⇒ Object

set current network map window title input: ip map addr



524
525
526
527
528
529
530
# File 'lib/main.rb', line 524

def set_map_window_title(mp)
  txt=mp
  if  txt && $network[txt] && $network[txt].name?()
    txt=$network[txt].name
  end
  $win.set_title("Map #{txt}")
end

#set_snmp(node, oid, value) ⇒ Object

set the value of the entry



78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
# File 'lib/monitor/client/snmp/snmp.rb', line 78

def set_snmp(node, oid, value)

  #get values from node network
  version=node.get_default_inherit_snmp_version()
  port=node.get_default_inherit_snmp_port()
  timeout=node.get_default_inherit_snmp_timeout()
  retr=node.get_default_inherit_snmp_retry()

  community_read = $config.read_community
  community_write = $config.write_community
  if node.("snmp")
    community_read, community_write = node.("snmp")
  end

  begin
    if oid ==nil || value == nil
      $log.error("Error in set_snmp_OID: oid/value is null")
      return "Error"
    end
    SNMP::Manager.open(:Host => node.ip, :Community => community_read, :WriteCommunity => community_write, :Version => get_snmp_version(version), :Port => port.to_i, :Timeout => timeout.to_i, :Retries => retr.to_i) do |manager|
      varbind=SNMP::VarBind.new(oid,SNMP::OctetString.new(value))
      response = manager.set(varbind)
      if response.error_status().to_s != "noError"
        return response.error_status().to_s
      end
    end
    return 0
  rescue Exception => msg
    $log.error("Error in set_snmp_OID: #{msg}")
    return "Error"
  end
end

#set_unbusyObject



1090
1091
1092
# File 'lib/main.rb', line 1090

def set_unbusy()
   $win.unbusy()
end

#ssdp_analyze(pkt) ⇒ Object

analyze udp packet to port 1900 trying to extract some upnp data



689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
# File 'lib/node_listener.rb', line 689

def ssdp_analyze(pkt)
  packet_info = [pkt.ip_saddr,  pkt.udp_dst]
  #we assume here dst port is set to default upnp port 1900
  #if pkt.udp_dst == 1900
  #puts "%s %s" % packet_info
  ssdp_body = pkt.udp_header.body
  #try to find the OS
  detected_os = "unknown"
  if ssdp_body.include?("M-SEARCH * HTTP/1.1") and ssdp_body.include?("ssdp:discover") and ssdp_body.include?("upnp:rootdevice")
    #puts "query"
    return [pkt.ip_saddr, detected_os]
  elsif ssdp_body.include?("HTTP/1.1 200 OK") and ssdp_body.include?("upnp:rootdevice")
    #puts "response"
    ssdp_body.each_line {|l|
      l.upcase!
      if l.include?("SERVER:")
        if l.include?("WINDOWS")
          detected_os = "windows"
        elsif l.include?("LINUX")
          detected_os = "linux"
        end
        return [pkt.ip_saddr, detected_os]
      end
    }
    return [pkt.ip_saddr, detected_os]
    #end
  end
  return nil
end

#switch_main_visibilityObject

switch main window visibility



716
717
718
719
720
721
722
723
724
725
# File 'lib/main.rb', line 716

def switch_main_visibility()
  if $icon
    $icon.set_blinking(false)
    if $win.visible?
      $win.hide
    else
      $win.show
    end
  end
end

#t_find_local_segment_pingingObject

listen for new host in local network (broadcast)



596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
# File 'lib/node_listener.rb', line 596

def t_find_local_segment_pinging()
  Thread.start {
    while $config.active_find_node_state
      sleep($config.active_find_node_delay.to_i)
      if !defined?($in_confirm_exit_window) || ($in_confirm_exit_window == false)
        mask=local_mask()
        mask = DEFAULT_CLASS_C_NETMASK if !mask
        for ip in broadcast_ping
          #puts "t_find_local_segment_pinging #{ip} #{mask}"
          #test if network was removed during the time
          if ($network_map_always == 1) and isValidIPv4($network_map_result) and !$network.has_key?($network_map_result)
            $network_map_always = 0
            $network_map_result = nil
          end
          if $host and $host[ip].nil?
            if !$config.visible() and !in_exception_list(ip)
              if $network_map_always == 0
                choose_network_map(ip, IPCalc.get_network_addr(ip, mask))
                while $network_map_result.nil?
                  sleep(2)
                end
              end
              if !$network_map_result.nil? and !$network_map_result.empty?
                if isValidIPv4($network_map_result)
                  map = $network_map_result
                  if $network.has_key?(map)
                    addhostentry(ip, mask, map)
                    sleep(2)
                  end
                else
                  add_node_def_exception_list(ip)
                end
              end
              if $network_map_always == 0
                $network_map_result = nil
              end
            end
          end
        end
      end
      sleep($config.active_find_node_delay.to_i)
    end
  }
end

#t_find_local_segment_scanningObject

active scanning to find new nodes



865
866
867
# File 'lib/node_listener.rb', line 865

def t_find_local_segment_scanning()

end

#t_find_local_segment_sniffingObject

passive scanning listen for new host in local network, sniffing for packets arp, lldp/cdp, upnp



724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
# File 'lib/node_listener.rb', line 724

def t_find_local_segment_sniffing()
  #run as root ?
  if Process.euid == 0
    begin
      require 'pcaprub'
      require 'packetfu'
    rescue LoadError => msg
      $log.error("Missing library #{msg}")
      return
    end

    iface = Pcap.lookupdev
    if iface
      Thread.start {
        cap =  PacketFu::Capture.new(:iface => iface, :start => false)
        begin
          cap.bpf(:filter => 'not ip')
        rescue
          $log.info("Can't set the bpf filter for sniff packets")
        end
        cap.start
        loop do
          cap.stream.each do |p|
            pkt = PacketFu::Packet.parse p
            if $config.passive_find_node_state and !$config.visible()
              if pkt.is_arp?
                #check if it's ethernet and arp reply
                if pkt.arp_hw == 1 and pkt.arp_opcode == 2
                  ip_mac_t = Array.new
                  ip_mac_t.push([pkt.arp_saddr_ip, pkt.arp_saddr_mac])
                  ip_mac_t.push([pkt.arp_daddr_ip, pkt.arp_daddr_mac])
                  ip_mac_t.each {|ip, mac|
                    $log.debug("t_find_local_segment_sniffing: ARP reply founds ip=#{ip} mac=#{mac}")
                    if isValidIPv4(ip) and !exist_host(ip) and !in_exception_list(ip)
                      if $network_map_always == 0
                        choose_network_map(ip)
                        while $network_map_result.nil?
                          sleep(2)
                        end
                      end
                      if !$network_map_result.nil? and !$network_map_result.empty?
                        if isValidIPv4($network_map_result)
                          map = $network_map_result
                          if $network.has_key?(map)
                            addhostentry(ip, 24, map)
                            sleep(2)
                            if $host[ip]
                              $host[ip].mac = mac
                            end
                          end
                        else
                          add_node_def_exception_list(ip)
                        end
                      end
                      if $network_map_always == 0
                        $network_map_result = nil
                      end
                    end
                  }
                end
              end
              #check for upnp ssdp packets
              if pkt.is_udp? and (pkt.udp_dst == 1900)
                result = ssdp_analyze(pkt)
                if !result.nil?
                  ip, os = result
                  $log.debug("t_find_local_segment_sniffing: SSDP founds ip=#{ip} os=#{os}")
                  if isValidIPv4(ip) and !exist_host(ip) and !in_exception_list(ip)                  
                    if $network_map_always == 0
                      choose_network_map(ip)
                      while $network_map_result.nil?
                        sleep(2)
                      end
                    end
                    if !$network_map_result.nil? and !$network_map_result.empty?
                      if isValidIPv4($network_map_result)
                        map = $network_map_result
                        if $network.has_key?(map)
                          addhostentry(ip, 24, map)
                          sleep(2)
                          if $host[ip] and (os != "unknown")
                            $host[ip].os = os
                          end
                        end
                      else
                        add_node_def_exception_list(ip)
                      end
                    end
                    if $network_map_always == 0
                      $network_map_result = nil
                    end                    
                  end
                end
              end
              begin
                if pkt.is_lldp?
                  $log.debug("t_find_local_segment_sniffing: LLDP founds ip=#{pkt.lldp_address} mac=#{pkt.lldp_saddr_mac}")
                  if (pkt.lldp_address_type_readable == "IPv4") and isValidIPv4(pkt.lldp_address) and !exist_host(pkt.lldp_address) and !in_exception_list(pkt.lldp_address)
                    if $network_map_always == 0
                      choose_network_map(pkt.lldp_address)
                      while $network_map_result.nil?
                        sleep(2)
                      end
                    end
                    if !$network_map_result.nil? and !$network_map_result.empty?
                      if isValidIPv4($network_map_result)
                        map = $network_map_result
                        if $network.has_key?(map)
                          addhostentry(pkt.lldp_address, 24, map)
                          sleep(2)
                          if $host[pkt.lldp_address]
                            $host[pkt.lldp_address].mac = pkt.lldp_saddr_mac
                            $host[pkt.lldp_address].name = pkt.lldp_system_name
                          end
                        end
                      else
                        add_node_def_exception_list(pkt.lldp_address)
                      end
                    end
                    if $network_map_always == 0
                      $network_map_result = nil
                    end
                  end
                end
              rescue NoMethodError
                #current gem version does not support lldp patch i sent
              end
            end
          end
        end
      }
    end
  else
    $log.error("t_find_local_segment_sniffing: Not enough privileges to sniff network packets, rerun as root")
    return
  end
end

#t_find_remote_new_hostObject



552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
# File 'lib/node_listener.rb', line 552

def t_find_remote_new_host ()
  Thread.start {
    while $config.active_find_node_state
      sleep($config.active_find_node_delay.to_i)
      $log.debug("in t_find_remote_new_host")
      $network.each_value {|node|
        if !$config.active_find_node_state
          break
        end
        if node.ip != ROOTMAPADDR
          lhost=broadcast_remote_ping(node.ip, node.netmask)
          #we secure the function call after
          if !defined?($in_confirm_exit_window) || ($in_confirm_exit_window == false)
            for ip in lhost
              #puts "#{ip} dans t_find_remote_new_host"
              add_host_entry_with_map(ip, node.netmask, node.ip)
            end
          end
        end
      }
      sleep($config.active_find_node_delay.to_i)
    end
  }
end

#t_find_ssdp_discoveryObject

threat which is sending SSDP discovery requests



644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
# File 'lib/node_listener.rb', line 644

def t_find_ssdp_discovery()
  if Process.euid != 0
    return
  end
  Thread.start {
    $log.debug("in t_find_ssdp_discovery")
    dest = "239.255.255.250"
    port = 1900      
    msearch =
    "M-SEARCH * HTTP/1.1\r\n" +
    "Host:#{dest}:#{port}\r\n" +
    "ST:upnp:rootdevice\r\n" +
    "Man:\"ssdp:discover\"\r\n" +
    "MX:3\r\n\r\n"
  
    udp_sock = UDPSocket.new
    while $config.passive_find_node_state
      begin
        udp_sock.bind("0.0.0.0", port)
      rescue Errno::EADDRINUSE
      rescue Errno::EINVAL
      rescue Exception => msg
        $log.error("in t_find_ssdp_discovery during udp binding: #{msg}")
      end
      begin
        udp_sock.send(msearch, 0, dest, port)
        res = nil
        1.upto(5) do
          res,addr,info = udp_sock.recvfrom(65535, 1.0)
          break if res and res =~ /^(Server|Location)/mi
          sleep(10)
          udp_sock.send msearch, 0, dest, port
        end
      rescue Exception => msg
        $log.error("in t_find_ssdp_discovery: #{msg}")
      end        
      sleep($config.passive_find_node_delay.to_i)
    end
  }
end

#tauto_save_mapObject

auto save map



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/node_listener.rb', line 9

def tauto_save_map()
	$log.debug("in tauto_save_map")
	Thread.start {
		while $config.auto_save_map
			for minute in 1..$config.auto_save_map_value.to_i
				sleep(60)
				if !$config.auto_save_map
					break
				end
			end
			$log.info("Auto Saving map every #{$config.auto_save_map_value} minutes launch")
	                write_xml()
		end
	del_monitoring_thread("Map autosaving")
	}
end

#test_monitored_custom(ip) ⇒ Object

verify by custom monitoring



241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
# File 'lib/cmd_parse.rb', line 241

def test_monitored_custom(ip)
  $log.debug "cmd_parse test_monitored_custom #{ip}"
  if $host[ip].custom_monitoring.size() > 0
    max_severity=UNKNOWN
    max_severity_description=nil
    $host[ip].custom_monitoring.each_value {|custom_mon|
      if custom_mon.active?()
        $log.debug("running custom #{custom_mon.name}")
        begin
          result_tmp=(eval custom_mon.name).new($host[ip])
          while (result_tmp.get_event_state_raw()==nil) do
            sleep(5)
          end

          if $status_value[result_tmp.get_event_state_raw()] > max_severity
            max_severity=$status_value[result_tmp.get_event_state_raw()]
            max_severity_description=result_tmp.get_event_description()
          end
          if result_tmp.get_event_description() != nil
            #if severity is unknown and we have a description; this should be an error report
            if result_tmp.get_event_state_raw() == $status.size()-1
              $event_win.add_event(EventWindow::CUSTOM_EVENT_TYPE, "ERR", $host[ip], "#{result_tmp.get_event_description()}")
            else
              $event_win.add_event(EventWindow::CUSTOM_EVENT_TYPE, get_level_from_status($status[result_tmp.get_event_state_raw()]), $host[ip], "#{result_tmp.get_event_description()}")
            end
          end
        rescue
          raise
        end
      end
    }
    #at this point max_severity contains the severity max found for all custom monitor enabled for this host
    $host[ip].set_custom_severity(max_severity)
  elsif $host[ip].custom_sev > UNMANAGED
    #no custom monitoring for this host
    $host[ip].set_custom_severity(UNMANAGED)
  end
end

#test_monitored_jmx(ip) ⇒ Object

verify if jmx ref threshold value is ok



421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
# File 'lib/cmd_parse.rb', line 421

def test_monitored_jmx(ip)
	$log.debug "cmd_parse test_monitored_jmx #{ip}"
	if $host[ip] && ($host[ip].jmx_monitoring.size() > 0)
		max_severity=UNKNOWN
		begin
		  $host[ip].jmx_monitoring.each_value {|jmx_mon|
			  if jmx_mon.active?()
				 begin
					#jmx can return multiple entries
					jmx_direct_table=""
					if jmx_mon.get_auth() == "None"
						jmx_direct_table=jmx_request($host[ip], jmx_mon.get_port(), "", "", jmx_mon.get_ref(), jmx_mon.get_attributes().keys.join(" "))
					else
						username, password = $host[ip].(jmx_mon.get_auth())
						jmx_direct_table=jmx_request($host[ip], jmx_mon.get_port(), username, password, jmx_mon.get_ref(), jmx_mon.get_attributes().keys.join(" "))
					end
					if jmx_direct_table[0] && !jmx_direct_table[0].match("^error|such file")
						max_severity_set=0
						jmx_mon.get_attributes().each_pair { |attr, attrmon|
						ind=-1
						fnd=false
						jmx_direct_table.each {|entr|
							ind+=1
							if entr.match("^#{attr}")
								fnd=true
								break
							end
						}

						if fnd
							if ind
								val=jmx_direct_table[ind].gsub(attr+": ","")
								jmx_oper="#{JmxAttributeMonitoring::TESTOP[attrmon.operator]}"
				 				if "#{jmx_oper}" == "="
					 				jmx_oper="=="
				 				end
								expr_test="#{val} #{jmx_oper} #{attrmon.value}"
								if eval(expr_test)
									print $status_value[attrmon.raw_severity()]," ", max_severity, "\n"
					 				if $status_value[attrmon.raw_severity()] > max_severity
						 				max_severity=$status_value[attrmon.raw_severity()]
										max_severity_set=1
							 		end
								end
							end
						end
						}
						if max_severity_set == 1
						   	$event_win.add_event(EventWindow::JMX_EVENT_TYPE, get_level_from_status($status[$status_value.index(max_severity)]), $host[ip], "Monitoring '#{jmx_mon.get_ref()}' matched")
						end
				 	else
						$log.error("Problem in JMX request on #{ip}, #{jmx_direct_table[0]}")
						$event_win.add_event(EventWindow::JMX_EVENT_TYPE, "ERR", $host[ip], "#{jmx_direct_table}")						
				 	end
				 rescue Exception => msg
					 $log.error("Problem in JMX request on #{ip}, validate '#{jmx_mon.get_ref()}' JMX Reference #{msg}")
					 return
				 end
			  end
		  }
		  #set the jmx severity to max find for this host
		  if max_severity > $host[ip].jmx_sev
			  $host[ip].set_jmx_severity(max_severity)
		  end
		rescue Exception => msg
			$log.error("Exception in test_monitored_jmx for #{ip}: #{msg}")
		end
	else
		if $host[ip]
				$host[ip].set_jmx_severity(UNMANAGED)
		end
	end
end

#test_monitored_ports(ip) ⇒ Object

verify if monitored ports are always open return -1 if ok or return the worst severity as constant



505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
# File 'lib/cmd_parse.rb', line 505

def test_monitored_ports(ip)
  $log.debug "cmd_parse test_monitored_ports #{ip}"
  #we assume here $host[ip].port is not nil
  if $host[ip].service.size() == 0
    return -1
  end

  #setting bad sev to critical by default
  bad_sev = $status.size
  sev_spe = $status.size
  failed = 0
  failed_str = ""
  
  $host[ip].service.each_value{|serv|
    if serv.monitor.to_i() == 1
      p1 = nil
      if serv.protocol == "tcp"
        p1 = Net::Ping::TCP.new(ip, serv.port)
      else
        p1 = Net::Ping::UDP.new(ip, serv.port)
      end
           
      if !p1.ping?
        sev_spe = $host[ip].get_service_sev(serv.protocol, serv.port)
	bad_sev = sev_spe if sev_spe < bad_sev
	failed_str += "#{serv.protocol}/#{serv.port} "
        failed += 1
      end      
    end
  }
  if failed > 0
    if bad_sev == $status.size
      $log.error("Service monitoring severity can't be found, setting critical")
      bad_sev = 0
    end
    $event_win.add_event(EventWindow::PORT_EVENT_TYPE, get_level_from_status($status[bad_sev]), $host[ip], "#{failed_str} not responding")
    return $status_value[bad_sev]
  end
  return -1  
end

#test_monitored_snmp(ip) ⇒ Object

verify if oid ref threshold value is ok



283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
# File 'lib/cmd_parse.rb', line 283

def test_monitored_snmp(ip)
  if $host[ip] && ($host[ip].snmp_monitoring.size() > 0)
    max_severity = UNKNOWN

    community_pub = $config.read_community
    community_priv = $config.write_community
    if $host[ip].("snmp")
      community_pub, community_priv = $host[ip].("snmp")
    end
    begin
      SNMP::Manager.open(:Host => ip, :Community => community_pub, :Version => get_snmp_version($host[ip].get_default_inherit_snmp_version()), :Port => $host[ip].get_default_inherit_snmp_port().to_i, :Timeout => $host[ip].get_default_inherit_snmp_timeout().to_i, :Retries => $host[ip].get_default_inherit_snmp_retry().to_i) do |manager|
        $host[ip].snmp_monitoring.each_value {|snmp_mon|
          if snmp_mon.active?()
            snmp_oper="#{snmp_mon.oper()}"
            if "#{snmp_mon.oper()}" == "="
              snmp_oper="=="
            end
            begin

              snmp_direct_value="#{snmp_mon.value(manager,$host[ip])}"
              #here snmp_direct_value can be a string and not an operation
              #check if a OID value in not known by the agent
              if !snmp_direct_value.include?("Null")
                expr_test=""
                if snmp_direct_value.match('^[\d.+*/ -]+$')
                  expr_test="#{snmp_direct_value} #{snmp_oper} #{snmp_mon.threshold}"
                else
                  expr_test="'#{snmp_direct_value}' #{snmp_oper} '#{snmp_mon.threshold}'"
                end
                if eval(expr_test)
                  if $status_value[snmp_mon.raw_severity] > max_severity
                    max_severity=$status_value[snmp_mon.raw_severity]
                  end
                  $event_win.add_event(EventWindow::SNMP_EVENT_TYPE, get_level_from_status($status[$status_value.index(max_severity)]), $host[ip], "Monitoring #{snmp_mon.oidref} matched")
                end
              else
                $log.error("Problem in SNMP request on #{ip}, seems OID used is unknown on remote agent")
                $event_win.add_event(EventWindow::SNMP_EVENT_TYPE, "ERR", $host[ip], "OID #{snmp_mon.oidref} used is unknown on remote agent")
              end
            rescue
              $log.error("Problem in SNMP request on #{ip}, validate #{snmp_mon.oidref} OID Reference")
              $event_win.add_event(EventWindow::SNMP_EVENT_TYPE, "ERR", $host[ip], "Problem validate #{snmp_mon.oidref} OID Reference")
              return
            end
          end
        }
        #set the snmp severity to max find for this host
        if max_severity > $host[ip].snmp_sev
          $host[ip].set_snmp_severity(max_severity)
        end
      end #manager
    rescue SNMP::RequestTimeout
      $log.debug("test_monitored_snmp: request timeout to #{ip} port: #{$host[ip].get_default_inherit_snmp_port().to_i} community: #{community_pub} snmp_version: #{get_snmp_version(node.get_default_inherit_snmp_version())}")              
    rescue Exception => msg
      $log.error("Exception in test_monitored_snmp for #{ip}: #{msg}")
    end
  else
    if $host[ip]
      $host[ip].set_snmp_severity(UNMANAGED)
    end
  end
end

#test_monitored_wmi(ip) ⇒ Object

verify if wmi ref threshold value is ok



349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
# File 'lib/cmd_parse.rb', line 349

def test_monitored_wmi(ip)
	$log.debug "cmd_parse test_monitored_wmi #{ip}"
	if $host[ip] && ($host[ip].wmi_monitoring.size() > 0)
		max_severity=UNKNOWN
		begin
		  $host[ip].wmi_monitoring.each_value {|wmi_mon|
			  if wmi_mon.active?()
				 wmi_oper="#{wmi_mon.oper()}"
				 if "#{wmi_mon.oper()}" == "="
					 wmi_oper="=="
				 end
				 begin
					#wml request can return multiple entries
					wmi_direct_table=wmi_mon.request($host[ip])
					if wmi_direct_table
							max_severity_set=0
							if wmi_oper == "Contain"
								if wmi_direct_table.include?(wmi_mon.value)
						 			if $status_value[wmi_mon.raw_severity] > max_severity
							 			max_severity=$status_value[wmi_mon.raw_severity]
										max_severity_set=1
								 	end
								end
							elsif wmi_oper == "Not contain"
								if !wmi_direct_table.include?(wmi_mon.value)
						 			if $status_value[wmi_mon.raw_severity] > max_severity
							 			max_severity=$status_value[wmi_mon.raw_severity]
										max_severity_set=1
								 	end
								end
							end
						if max_severity_set == 1
					   	   $event_win.add_event(EventWindow::WMI_EVENT_TYPE, get_level_from_status($status[$status_value.index(max_severity)]), $host[ip], "Monitoring '#{wmi_mon.wmiref}' matched for #{wmi_mon.value}")
						end
				 	else
						$log.error("Problem in WMI request on #{ip}, seems WML used is unknown on remote agent")
						$event_win.add_event(EventWindow::WMI_EVENT_TYPE, "ERR", $host[ip], "WML used is unknown on remote agent")						
				 	end
				 rescue Exception => msg
					 $log.error("Problem in WMI request on #{ip}, validate '#{wmi_mon.wmiref}' WMI Reference")
					 return
				 end
			  end
		  }
		  #set the wmi severity to max find for this host
		  if max_severity > $host[ip].wmi_sev
			  $host[ip].set_wmi_severity(max_severity)
		  end
		rescue Exception => msg
			$log.error("Exception in test_monitored_wmi for #{ip}: #{msg}")
		end
	else
		if $host[ip]
				$host[ip].set_wmi_severity(UNMANAGED)
		end
	end
end

#tfindrangeremotehost(ip_begin, ip_end) ⇒ Object

try to find new host in a given range IP addr



580
581
582
583
584
585
586
587
588
589
590
591
# File 'lib/node_listener.rb', line 580

def tfindrangeremotehost (ip_begin, ip_end)
  Thread.start {
		$log.debug("in tfindrangeremotehost")
		lhost=range_remote_ping(ip_begin, ip_end)
		if !defined?($in_confirm_exit_window) || ($in_confirm_exit_window == false)
		  for ip in lhost
		#puts "findrangeremotehost #{ip}"
	   	 add_host_entry_with_map(ip, 24, get_map())
		  end
		end
  }
end

#tfindremotehost(map, mask) ⇒ Object

try to find new host in another network



541
542
543
544
545
546
547
548
549
550
# File 'lib/node_listener.rb', line 541

def tfindremotehost (map, mask)
  Thread.start {
    lhost=broadcast_remote_ping(map, mask)
    if !defined?($in_confirm_exit_window) || ($in_confirm_exit_window == false)
      for ip in lhost
        add_host_entry_with_map(ip, mask, map)
      end
    end
  }
end

#thread_startingObject



1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
# File 'lib/main.rb', line 1010

def thread_starting()
  $threads=ThreadGroup.new()
  $thread_list=Hash.new

  if $config.port_mon
    #thread to listen to monitored port & heartbeat host
    add_monitoring_thread("Port monitoring", tmonitorport())
  end
  if $config.snmp_mon
    #thread to listen to monitored snmp oid refs
    add_monitoring_thread("Snmp monitoring", tmonitorsnmp())
  end
  if $config.wmi_mon
    #thread to listen to monitored wmi refs
    add_monitoring_thread("Wmi monitoring", tmonitorwmi())
  end
  if $config.custom_mon
    #thread to listen to monitored custom cmd
    add_monitoring_thread("Custom monitoring", tmonitorcustom())
  end
  if $config.jmx_mon
    #thread to listen to monitored jmx cmd
    add_monitoring_thread("JMX monitoring", tmonitorjmx())
  end
  if $config.active_find_node_state
    #thread to find new host in local network with broacast ping	
    add_monitoring_thread("Local ping", t_find_local_segment_pinging())
    #thread to find new host in remote network with nmap ping
    add_monitoring_thread("Remote ping", t_find_remote_new_host())
  end
  if $config.passive_find_node_state
	#thread to find new host in local segment sniffing for arp/lldp/dhcp packets
	add_monitoring_thread("Local sniffing", t_find_local_segment_sniffing())
	#thread which is sending SSDP query	
	add_monitoring_thread("SSDP query", t_find_ssdp_discovery())      
  end
  if $config.mac_state
    #thread to find MAC address
    add_monitoring_thread("Find mac", tmacip())
  end
  if $config.node_resolving
    #thread to resolv ip into name
    add_monitoring_thread("Resolve ip to name", tresolvip())
    #thread to resolve ip into netbios name
    add_monitoring_thread("Resolve ip to netbios", tresolvnetbiosname())
    #thread to find os with fingerprinting
    add_monitoring_thread("Find os", tresolvos())
	#thread to find nodes with snmp
    add_monitoring_thread("Find snmp", tresolvesnmp())	
  end

  if $config.auto_save_map
    add_monitoring_thread("Map autosaving", tauto_save_map())
  end
  $syslog_capture = SyslogCapture.new()
  $snmptrap_capture = SnmpTrapCapture.new()
  $im_daemon = XmppBot.new()
  $irc_daemon = IrcBot.new()
end

#thread_stoppingObject



1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
# File 'lib/main.rb', line 1070

def thread_stopping()
  $threads.list.each {|thr|
    Thread.kill(thr)
    Gtk.thread_flush
  }
  #kill syslog daemon if needed
  $syslog_capture.stop() unless $syslog_capture == nil
  $snmptrap_capture.stop() unless $snmptrap_capture == nil
  $im_daemon.stop() unless $im_daemon == nil
  $irc_daemon.stop() unless $irc_daemon == nil
end

#tmacipObject

try to find a mac address for an IP



482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
# File 'lib/node_listener.rb', line 482

def tmacip ()
  Thread.start {
    while $config.mac_state
      sleep($config.mac_delay.to_i) #wait before all window are maps
      ip_table=$host.keys
      for ip in ip_table
        if !$config.mac_state
          break
        end
        if !defined?($in_confirm_exit_window) || ($in_confirm_exit_window == false)
          if $host[ip] && $host[ip].mac == "(noarp)"
            begin
              timeout($config.mac_delay.to_i) {
                Thread.start {
                  res=mac(ip)
                  if res != ""
                    $host[ip].mac = res
                    $host[ip].change_label()
                  end
                }
                sleep(5)
              }
            rescue
              $log.info("difficulty to find MAC address for #{ip}")
            end
          else
            if $config.mac_lock #we verify mac address
              begin
                timeout($config.mac_delay.to_i) {
                  Thread.start {
                    #trying to get the mac addr using the arp table or snmp request
                    res=mac(ip)
                    if res != ""
                      if $host[ip] && $host[ip].mac != res && $host[ip].status != CRITICAL
                        $host[ip].set_avail_severity(MINOR)
                        $event_win.add_event(EventWindow::AVAIL_EVENT_TYPE, "WARN", $host[ip], "Hardware MAC address changed")
                      else
                        if $host[ip].status == MINOR
                          $host[ip].set_avail_severity(CRITICAL)
                        end
                      end
                    end
                  }
                  sleep(5)
                }
              rescue
              end
            end
          end
        end
      end
      sleep($config.mac_delay.to_i)
    end
  }
end

#tmonitorcustomObject

monitor custom



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/node_listener.rb', line 29

def tmonitorcustom()
	Thread.start {
   	while $config.custom_mon
			  $log.debug("in tmonitorcustom every #{$config.custom_mon_delay} second")
			  sleep($config.custom_mon_delay.to_i)
			  ip_table=$host.keys
			  for ip in ip_table
					if !$config.custom_mon
						break
					end
				  begin
					  if $host[ip].status != UNMANAGED
						  test_monitored_custom(ip)
					  end
				  rescue Exception => msg
				     $log.error("Custom monitor: #{msg}")
				     $event_win.add_event(EventWindow::CUSTOM_EVENT_TYPE, "ERR", $host[ip], msg)
				  end
			  end
		end
	}
end

#tmonitorjmxObject

monitor jmx refs



107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
# File 'lib/node_listener.rb', line 107

def tmonitorjmx()
	Thread.start {	
	   	while $config.jmx_mon
		  $log.debug("in tmonitorjmx every #{$config.jmx_mon_delay} second")
		  sleep($config.jmx_mon_delay.to_i)
		  ip_table=$host.keys
		  for ip in ip_table
				if !$config.jmx_mon
					break
				end
				begin
					if $host[ip] && ($host[ip].status != UNMANAGED)
						test_monitored_jmx(ip)
					end
				rescue Exception => msg
					$log.error("tmonitorjmx: #{msg}")
					$event_win.add_event(EventWindow::JMX_EVENT_TYPE, "INFO", $host[ip], msg)
				end
		  end
		end
	}
end

#tmonitorportObject

monitor host and service(s)



133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
# File 'lib/node_listener.rb', line 133

def tmonitorport()
  Thread.start {
    while $config.port_mon
      $log.debug("in tmonitorport every #{$config.port_mon_delay} second")
      sleep($config.port_mon_delay.to_i)
      #retry already known hosts, if NORMAL test his monitored ports
      ip_table=$host.keys
      for ip in ip_table
        if !defined?($in_confirm_exit_window) || ($in_confirm_exit_window == false)
          if $host[ip] != nil && $host[ip].status != UNMANAGED
            #puts "trying .... #{ip}"
            if ping(ip)
              #test monitored ports
              #puts "ping ok here #{ip} #{$host[ip].service.size()}"
              if $config.port_mon && $host[ip] && ($host[ip].service.size() > 0)
                #test if monitored ports are ok
                sev_st = test_monitored_ports(ip)
                if sev_st <= 0
                  $host[ip].set_service_severity(NORMAL)
                else
                  $host[ip].set_service_severity(sev_st)
                end
              end
              #host is up
              if $host[ip] && $host[ip].avail_sev != NORMAL
                $host[ip].set_avail_severity(NORMAL)
                $event_win.add_event(EventWindow::AVAIL_EVENT_TYPE, "INFO", $host[ip], "Ping OK")
              end
            else
              #puts "ping nok here #{ip} #{$host[ip].service.size()}"
              #test monitored ports here too, as the ping can be disabled but services up
              if $config.port_mon && $host[ip] && ($host[ip].service.size() > 0)
                #test if monitored ports are ok
                sev_st = test_monitored_ports(ip)
                if sev_st <= 0
                  $host[ip].set_service_severity(NORMAL)
                else
                  $host[ip].set_service_severity(sev_st)
                end
              end
              #host is down
              if $host[ip] != nil
                #puts "ping nok #{ip}"
                if $host[ip].avail_sev != CRITICAL
                  $host[ip].set_avail_severity(CRITICAL)
                end
		#here we only push the event when only the availability sev is set
		if (($host[ip].avail_sev == CRITICAL) and ($host[ip].snmp_sev <= UNMANAGED) and ($host[ip].custom_sev <= UNMANAGED) and ($host[ip].trap_sev <= UNMANAGED) and ($host[ip].service_sev <= UNMANAGED) and ($host[ip].wmi_sev <= UNMANAGED) and ($host[ip].syslog_sev <= UNMANAGED) and ($host[ip].jmx_sev <= UNMANAGED))
                  $event_win.add_event(EventWindow::AVAIL_EVENT_TYPE, "PANIC", $host[ip], "Ping KO")
		end
              end
            end
          end
        end
      end
    end
  }
end

#tmonitorsnmpObject

monitor snmp oid refs



55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/node_listener.rb', line 55

def tmonitorsnmp()
	Thread.start {
   	while $config.snmp_mon
		  $log.debug("in tmonitorsnmp every #{$config.snmp_mon_delay} second")
		  sleep($config.snmp_mon_delay.to_i)
		  ip_table=$host.keys
		  for ip in ip_table
				if !$config.snmp_mon
					break
				end
				begin
					if $host[ip] && ($host[ip].status != UNMANAGED)
						test_monitored_snmp(ip)
					end
				rescue Exception => msg		
					$log.error(msg)
					$event_win.add_event(EventWindow::SNMP_EVENT_TYPE, "INFO", $host[ip], msg)
				end
		  end
		end
	}
end

#tmonitorwmiObject

monitor wmi refs



81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
# File 'lib/node_listener.rb', line 81

def tmonitorwmi()
	Thread.start {	
	   	while $config.wmi_mon
		  $log.debug("in tmonitorwmi every #{$config.wmi_mon_delay} second")
		  sleep($config.wmi_mon_delay.to_i)
		  ip_table=$host.keys
		  for ip in ip_table
				if !$config.wmi_mon
					break
				end
				begin
					if $host[ip] && ($host[ip].status != UNMANAGED)
						test_monitored_wmi(ip)
					end
				rescue Exception => msg	
					$log.error(msg)
					$event_win.add_event(EventWindow::WMI_EVENT_TYPE, "INFO", $host[ip], msg)	
				end
		  end
		end
	}
end

#tresolvesnmpObject

snmp discovery read arp, route, interface from a snmp host



316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
# File 'lib/node_listener.rb', line 316

def tresolvesnmp()
  Thread.start {
    while $config.node_resolving
      $log.debug("in tresolvesnmp every #{$config.node_resolving_delay.to_i} second")
      sleep($config.node_resolving_delay.to_i) #wait before all window are maps
      ip_table=$host.keys
      for ip in ip_table
        if !$config.node_resolving
          break
        end
        node = $host[ip]
        if node and (!defined?($in_confirm_exit_window) || ($in_confirm_exit_window == false))
          #code here
          community_pub = $config.read_community
          community_priv = $config.write_community
          if node.("snmp")
            community_pub, community_priv = node.("snmp")
          end

          new_node = Struct.new(:ip, :mac, :netmask, :status)
          new_node_array = Array.new
          
          begin
            new_node_array.clear
            SNMP::Manager.open(:Host => ip, :Community => community_pub, :Version => get_snmp_version(node.get_default_inherit_snmp_version()), :Port => node.get_default_inherit_snmp_port().to_i, :Timeout => node.get_default_inherit_snmp_timeout().to_i, :Retries => node.get_default_inherit_snmp_retry().to_i) do |manager|

              #extract ip addr from interfaces
              ip_addr_t = Array.new
              interface_netmask_h = Hash.new
              manager.walk("1.3.6.1.2.1.4.20.1.1") {|vb|
                ip_addr_t.push vb.value.to_s
              }
              ip_addr_t.each {|ip|
                interface_id = nil
                netmask_addr = nil
                mac_addr = nil
                #unknown status
                status = 4
                #get interface id
                response = manager.get("1.3.6.1.2.1.4.20.1.2.#{ip}")
                response.each_varbind {|vb|
                  interface_id = vb.value.to_i
                }
                #extract mac addr for these interfaces based on ifPhysAddress
                response = manager.get("1.3.6.1.2.1.2.2.1.6.#{interface_id}")
                response.each_varbind {|vb|
                  mac_addr = vb.value.unpack('H*').join.scan(/.{2}|.+/).join(":")
                }
                #extract interface status
                response = manager.get("1.3.6.1.2.1.2.2.1.8.#{interface_id}")
                response.each_varbind {|vb|
                  status = vb.value.to_i
                }
                #get netmask
                response = manager.get("1.3.6.1.2.1.4.20.1.3.#{ip}")
                response.each_varbind {|vb|
                  netmask_addr = vb.value.to_s
                }
                interface_netmask_h[interface_id] = netmask_addr unless interface_id.nil?
                if mac_addr.nil? or mac_addr.empty? or (mac_addr == NILMAC)
                  mac_addr = Node::NOARP_PROPERTY
                end
                #print ip, " ", mac_addr, " ", netmask_addr, " ", interface_id, "\n"
                new_node_array.push new_node.new(ip, mac_addr, netmask_addr, status)
              }
              #propagate the search if requested
              if $config.active_find_node_state              
                status = 4
                manager.walk("1.3.6.1.2.1.4.22.1.2") { |vb|
                  #remove mib header and extract interface id and ip
                  ip_from_mib = vb.name.to_s.match(/^.+\.(\d+)\.(\d+\.\d+\.\d+\.\d+)$/)
                  interface_id = $1.to_i
                  ip_from_mib = $2.to_s
                  mac_from_mib = vb.value.unpack('H*').join.scan(/.{2}|.+/).join(":")
  
                  mask = DEFAULT_CLASS_C_NETMASK
                  if (interface_id >=0) and interface_netmask_h[interface_id]
                    mask = interface_netmask_h[interface_id]
                  end
                  #print ip_from_mib," ",mac_from_mib," ", mask, "\n"
                  new_node_array.push new_node.new(ip_from_mib, mac_from_mib, mask, status)
                }
              end

              new_node_array.each {|nnode|                
                if isValidIPv4(nnode.ip) and (nnode.mac != NILMAC) and isValidMac(nnode.mac)
                  if $host[nnode.ip]
                    #node already exists, check the mac
                    if $host[nnode.ip].mac != Node::NOARP_PROPERTY
                      if $host[nnode.ip].mac != nnode.mac
                        $event_win.add_event(EventWindow::AVAIL_EVENT_TYPE, "WARN", $host[nnode.ip], "Hardware MAC address collision, find #{nnode.mac}")
                      end
                    else
                      #mac is not set for this node at this point, so adding it
                      $host[nnode.ip].mac = nnode.mac
                      #ifOperStatus = The current operational state of the interface
                      #Values
                      #1 : up
                      #2 : down
                      #3 : testing
                      #4 : unknown
                      #5 : dormant
                      #6 : notPresent
                      #7 : lowerLayerDown
                      if nnode.status == 1
                        $host[nnode.ip].set_avail_severity(NORMAL)
                      elsif nnode.status == 2
                        $host[nnode.ip].set_avail_severity(CRITICAL)
                      end
                    end
                  else
                    if !$config.visible() and !in_exception_list(nnode.ip)
                      #node is not existing
                      if ($network_map_always == 1) and isValidIPv4($network_map_result) and !$network.has_key?($network_map_result)
                        $network_map_always = 0
                        $network_map_result = nil
                      end
                      if $network_map_always == 0
                        choose_network_map(nnode.ip)
                        while $network_map_result.nil?
                          sleep(2)
                        end
                      end
                      if !$network_map_result.nil? and !$network_map_result.empty?
                        if isValidIPv4($network_map_result)
                          map = $network_map_result
                          if $network.has_key?(map)
                            #mask depends on the interface where we found this node ip
                            if nnode.status == 1
                              addhostentry(nnode.ip, nnode.netmask, map, nnode.mac, NORMAL)
                            elsif nnode.status == 2
                              addhostentry(nnode.ip, nnode.netmask, map, nnode.mac, CRITICAL)
                            else
                              addhostentry(nnode.ip, nnode.netmask, map, nnode.mac)
                            end
                            sleep(2)
                          end
                        else
                          add_node_def_exception_list(nnode.ip)
                        end
                      end
                      if $network_map_always == 0
                        $network_map_result = nil
                      end
                    end
                  end
                end
              }
            end #new_node_array
          rescue SNMP::RequestTimeout
            $log.debug("tresolvesnmp: request timeout to #{ip} port: #{node.get_default_inherit_snmp_port().to_i} community: #{community_pub} snmp_version: #{get_snmp_version(node.get_default_inherit_snmp_version())}")
          rescue Errno::ENETUNREACH
            $log.error("tresolvesnmp: network is unreachable")
          rescue Exception => msg
            $log.error("tresolvesnmp: #{msg}\n#{msg.backtrace.join("\n")}")
          end
        end
        sleep($config.node_resolving_delay.to_i)
      end
    end
  }
end

#tresolvipObject

try to find a name for an IP



270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
# File 'lib/node_listener.rb', line 270

def tresolvip()
	Thread.start {
		while $config.node_resolving
				  $log.debug("in tresolvip every #{$config.node_resolving_delay.to_i} second")
				  sleep($config.node_resolving_delay.to_i) #wait before all window are maps
					ip_table=$host.keys
					for ip in ip_table
						if !$config.node_resolving
							break
						end
					  if !defined?($in_confirm_exit_window) || ($in_confirm_exit_window == false)
						 if $host[ip] && !$host[ip].dns_name?
							 begin
								 timeout($config.node_resolving_delay.to_i) {
				       				 Thread.start {
									 #puts "in resolv ip #{ip}"
										begin
					        				res=Resolv.getname("#{ip}").to_s
						 					if res != ""
										 		#puts "resolved! #{res}"
						  	 			 		$host[ip].dns_name = res
										 		$host[ip].change_label()
											end
										rescue Resolv::ResolvError
										  $log.debug("tresolvip: can't find dns name for address #{ip}");
										rescue Errno::ENETUNREACH
										  $log.error("tresolvip: network is unreachable");
										end
           							 }
				      			sleep(5)
    							 }
  							 rescue
								 $log.error("Difficulty to resolv #{ip}, add it to your /etc/hosts file")
							 end
						 end
					  end
				  end
          sleep($config.node_resolving_delay.to_i)
		end
	}
end

#tresolvnetbiosnameObject

try to find a netbios name for an IP



234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
# File 'lib/node_listener.rb', line 234

def tresolvnetbiosname()
	Thread.start {
		while $config.node_resolving
			sleep($config.node_resolving_delay.to_i) #wait before all window are maps
			  ip_table=$host.keys
			  for ip in ip_table
				if !$config.node_resolving
					break
				end
			  if !defined?($in_confirm_exit_window) || ($in_confirm_exit_window == false)
				  if $host[ip] && $host[ip].netbios_name == "(noname)"
					  begin
						  timeout($config.node_resolving_delay.to_i) {
				       		  Thread.start {
				        	  		  res=ip2netbiosname("#{ip}")
						 	  		  if res != nil 
						  	 			  $host[ip].netbios_name = res
										  $host[ip].change_label()
							  		  end
           					  }
				      	 sleep(5)
    					  }
  					  rescue
						  $log.error("Difficulty to resolv #{ip} netbios name")
					  end
				  end
				end
			end
         sleep($config.node_resolving_delay.to_i)
		end
	}
end

#tresolvosObject

try to find os for given ip



195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
# File 'lib/node_listener.rb', line 195

def tresolvos()
	Thread.start {
		while $config.node_resolving
			$log.debug("in tresolos #{$config.node_resolving_delay.to_i} second")
			sleep($config.node_resolving_delay.to_i) #wait before all window are maps
			ip_table=$host.keys
			for ip in ip_table
				if !$config.node_resolving
					break
				end
			  if !defined?($in_confirm_exit_window) || ($in_confirm_exit_window == false)
				  #puts "for #{ip}"
				  if $host[ip] && ($host[ip].os == "unknown") && ($host[ip].status != CRITICAL) && ($host[ip].status != UNMANAGED)
					  begin
						  Timeout::timeout($config.node_resolving_delay.to_i) do |p|
				       		  Thread.start {
				        		 res=osfingerprint("#{ip}")
						 		 if res != "" && res != nil
						  	 	  $host[ip].os = res unless !$host[ip]
								  $host[ip].change_label() unless !$host[ip]
                          $host[ip].reload unless !$host[ip]
								 end
           					  }
				      	 sleep(p)
    					  end
  					  rescue Timeout::Error
						  $log.debug("tresolvos(): difficulty to find OS for address #{ip}")
					  end					
				  end
				end
			end
         sleep($config.node_resolving_delay.to_i)
		end
	}
end

#txtlvl_to_loggerlvl(str) ⇒ Object

return logger module level according to event log severity



212
213
214
215
216
217
218
219
220
221
222
223
224
225
# File 'lib/gnms.rb', line 212

def txtlvl_to_loggerlvl(str)
	case str
	when "Debug"
		return Logger::DEBUG
	when "Info"
		return Logger::INFO
	when "Warning"
		return Logger::WARN
	when "Error"
		return Logger::ERROR
	else
		return Logger::INFO
	end
end

#unwantednodewinObject

unwanted node window



805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
# File 'lib/gui/adddelnode.rb', line 805

def unwantednodewin()
  if $win == nil
    return
  end
  
  unwtdwin=Gtk::Window.new
  unwtdwin.set_transient_for($win)
  unwtdwin.set_title("Unwanted node")
  unwtdwin.set_size_request(250, 160)
  unwtdwin.set_modal(true)

  unwtdwin.signal_connect("key_press_event") {|w,e|
    if e.keyval == Gdk::Keyval::GDK_Escape
      unwtdwin.destroy
    end
  }

  frame = Gtk::Frame::new("Del exception")
  frame.border_width=10
  frame.show
  vbox_root=Gtk::VBox::new
  vbox_root.show
  unwtdwin.add vbox_root
  vbox_root.add frame
  vbox = Gtk::VBox.new
  vbox.show
  frame.add vbox

  table = Gtk::Table.new(2,2,false)
  table.set_row_spacings(5)
  table.set_size_request(-1,15)
  table.show

  label_value = Gtk::Label.new "Value"
  label_value.show
  combo_value=Gtk::ComboBox.new
  $node_exception_list.sort.each do |str|
    combo_value.append_text(str)
  end
  combo_value.set_active(0)
  combo_value.show

  table.attach(label_value,0,1,0,1)
  table.attach(combo_value,1,2,0,1)
  
  label_map_exception = Gtk::Label.new "Always map new node"
  label_map_exception.show
  check_map = Gtk::CheckButton.new
  if $network_map_always == 1
    check_map.set_active true
  else
    check_map.set_active false    
  end
  check_map.show
  check_map.signal_connect("toggled") {
    $network_map_always = check_map.active? ? 1 : 0        
  }

  table.attach(check_map,0,1,1,2)
  table.attach(label_map_exception,1,2,1,2)  
  
  del_button = Gtk::Button.new(Gtk::Stock::REMOVE)
  del_button.show
  del_button.signal_connect("clicked") {
    if combo_value.active >= 0
      del_node_def_exception_list(combo_value.active_text)
      combo_value.remove_text(combo_value.active)
      combo_value.set_active(0)
    end
  }

  close_button = Gtk::Button.new(Gtk::Stock::CLOSE)
  close_button.show
  close_button.signal_connect("clicked") {
    unwtdwin.destroy
  }

  bbox =Gtk::HBox::new(FALSE, 10)
  bbox.border_width=10
  bbox.show

  del_button.set_flags(Gtk::Widget::CAN_DEFAULT)
  bbox.pack_start(del_button, TRUE, TRUE, 0)
  close_button.set_flags(Gtk::Widget::CAN_DEFAULT)
  bbox.pack_start(close_button, TRUE, TRUE, 0)

  vbox.pack_start(table, FALSE, TRUE)
  separator = Gtk::HSeparator::new()
  separator.show
  vbox_root.pack_start(separator, FALSE, TRUE, 0)
  vbox_root.pack_start(bbox, FALSE, TRUE, 0)

  unwtdwin.show
end

#verify_delnodewin(node) ⇒ Object

window to delete an host



304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
# File 'lib/gui/adddelnode.rb', line 304

def verify_delnodewin(node)
  
	#test if is not the root network
	if !node || (node.map == nil)
		return
	end

	mode=1
	if node.class == Array
		#multiple nodes!
		mode=2
	end

  if $config.confirm_delete
	  label=""
	  if mode == 1
		  if node.ip == ""
   		 label = "Do you really want to delete this node ?"
		  else
   		 label = "Do you want to delete '#{node.ip}' ?"
		  end
		else
			#test if there more than 1 node in the array
			if node.size > 1
				label = "Do you really want to delete these nodes ?"
			else
				label = "Do you want to delete '#{node[0].ip}' ?"		
			end
     end
     dialog = Gtk::MessageDialog.new($win, Gtk::Dialog::DESTROY_WITH_PARENT,
                           	 Gtk::MessageDialog::QUESTION,
                           	 Gtk::MessageDialog::BUTTONS_YES_NO,
                           	 label)
	  dialog.run do |r|
		  dialog.destroy
		  if r == Gtk::Dialog::RESPONSE_YES then
			  if mode == 1
   			$event_win.add_event(EventWindow::CORE_EVENT_TYPE, "INFO", node, "Host removed")
   			node.delete()
			   #update map
			   #$network[node.map].update_status()
			  else
				  node.each {|n|
   				 $event_win.add_event(EventWindow::CORE_EVENT_TYPE, "INFO", n, "Host removed")
   				 n.delete()
				  }
			  	  #$network[n[0].map].update_status() unless n[0] == nil
			  end
			  return 1
		  end
	  end
	else
		#dont show confirm popup and delete anyway
		if mode == 1
   	 $event_win.add_event(EventWindow::CORE_EVENT_TYPE, "INFO", node, "Host removed")
   	 node.delete()
		else
			node.each {|n|
   		  $event_win.add_event(EventWindow::CORE_EVENT_TYPE, "INFO", n, "Host removed")
   		  n.delete()
			}
		end
		return 1
	end
	return 0
end

#verify_system_confObject

check ruby and gtk version



192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
# File 'lib/gnms.rb', line 192

def verify_system_conf()
	ruby_cmd_version = RUBY_VERSION 
        $log.info("Using Ruby version #{RUBY_VERSION}")
	ruby_version="^1\.[89]"
	if ruby_cmd_version.match(ruby_version)
		if (defined? Gtk) and !Gtk.check_version(2,4,0)
			return 0
		else
			$log.error("This tool needs at least GTK version 2.4")
		end
	else
		$log.error("This tool needs at least Ruby 1.8")
	end
	return 1
end

#walk_snmp_OID(node, oid) ⇒ Object

return an array of the value of the entry



44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/monitor/client/snmp/snmp.rb', line 44

def walk_snmp_OID(node, oid)

  #get values from node network
  version=node.get_default_inherit_snmp_version()
  port=node.get_default_inherit_snmp_port()
  timeout=node.get_default_inherit_snmp_timeout()
  retr=node.get_default_inherit_snmp_retry()

  community_read = $config.read_community
  community_write = $config.write_community
  if node.("snmp")
    community_read, community_write = node.("snmp")
  end

  begin
    snmp_manager=SNMP::Manager.open(:Host => node.ip, :Community => community_read, :WriteCommunity => community_write, :Version => get_snmp_version(version), :Port => port.to_i, :Timeout => timeout.to_i, :Retries => retr.to_i) do |manager|
      resultt=[]
      manager.walk(oid) {|vb|
        resultt.push(vb.to_s)
      }
      return resultt
    end
  rescue SNMP::RequestTimeout
    $log.debug("Error in get_snmp_OID: #{node.ip} not responding")
    return "Error"
  rescue Exception => msg
    $log.error("Error in get_snmp_OID: #{msg}")
    return "Error"
  end
end

#window_set_rgb(r, g, b) ⇒ Object

set map window background rgb color



649
650
651
652
653
654
655
# File 'lib/main.rb', line 649

def window_set_rgb(r, g, b)
  style=Gtk::Style.new
  style.set_bg(Gtk::STATE_NORMAL, r, g, b)
  style.set_bg(Gtk::STATE_ACTIVE, r, g, b)
  style.set_bg(Gtk::STATE_PRELIGHT, r, g, b)
  $win.set_style style
end

#wmi_request(login, password, host, wml) ⇒ Object

wmi request using external wmic command



410
411
412
413
414
415
416
# File 'lib/cmd_parse.rb', line 410

def wmi_request(, password, host, wml)
	if ($config.wmic_path != nil) && ($config.wmic_path != "")
		rs=`#{$config.wmic_path} -U #{}%#{password} //#{host} "#{wml}" 2>/dev/null`
		return rs.split(/\n/)
	end
	return Array.new	
end

#write_xml(fic_name = "#{CONF_DIR}/#{DEFAULTHOSTDBFILE}") ⇒ Object



2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
# File 'lib/node_db.rb', line 2466

def write_xml(fic_name="#{CONF_DIR}/#{DEFAULTHOSTDBFILE}")
  set_busy()
  $log.info("Saving nodes to XML file #{fic_name}")
  begin
    tf=Tempfile.new(File.basename(fic_name))
  rescue Exception=>msg
    $log.error("Error in write_xml when tried to generate a temp file name")
    return
  end


  #we write first of all the root of all network = ROOTMAPADDR
  tf.puts(network_to_xml(ROOTMAPADDR))

  #1st: we write the node network
  $network.each_key {|ip|
    if ip != ROOTMAPADDR
      tf.puts(network_to_xml(ip))
    end
  }

  #2nd: we write the node host
  $host.each_key {|ip|
    doc = Document.new
    doc.add_element("Host")

    i=1
    doc.root.add_element("uuid")
    doc.root.elements[i].text = $host[ip].uuid
    i+=1
    doc.root.add_element("ip")
    doc.root.elements[i].text = $host[ip].ip
    i+=1
    doc.root.add_element("mask")
    doc.root.elements[i].text = $host[ip].netmask
    i+=1
    doc.root.add_element("map")
    doc.root.elements[i].text = $host[ip].map
    i+=1
    doc.root.add_element("mac")
    doc.root.elements[i].text = $host[ip].mac
    i+=1
    doc.root.add_element("dns_name")
    doc.root.elements[i].text = $host[ip].dns_name
    i+=1
    doc.root.add_element("netbios_name")
    doc.root.elements[i].text = $host[ip].netbios_name
    i+=1
    doc.root.add_element("services")
    services=doc.root.elements[i]
    $host[ip].service.each_value {|serv|
      service=Element.new("service")
      service.add_element("protocol")
      service.elements["protocol"].text = serv.protocol
      service.add_element("port")
      service.elements["port"].text = serv.port
      service.add_element("name")
      service.elements["name"].text = serv.name
      service.add_element("monitor")
      service.elements["monitor"].text = serv.monitor
      services.elements << service
    }
    i+=1
    doc.root.add_element("avail_sev")
    doc.root.elements[i].text = $host[ip].avail_sev
    i+=1
    doc.root.add_element("snmp_sev")
    doc.root.elements[i].text = $host[ip].snmp_sev
    i+=1
    doc.root.add_element("custom_sev")
    doc.root.elements[i].text = $host[ip].custom_sev
    i+=1
    doc.root.add_element("trap_sev")
    doc.root.elements[i].text = $host[ip].trap_sev
    i+=1
    doc.root.add_element("service_sev")
    doc.root.elements[i].text = $host[ip].service_sev
    i+=1
    doc.root.add_element("wmi_sev")
    doc.root.elements[i].text = $host[ip].wmi_sev
    i+=1
    doc.root.add_element("syslog_sev")
    doc.root.elements[i].text = $host[ip].syslog_sev
    i+=1
    doc.root.add_element("jmx_sev")
    doc.root.elements[i].text = $host[ip].jmx_sev
    i+=1
    doc.root.add_element("x")
    doc.root.elements[i].text = $host[ip].x
    i+=1
    doc.root.add_element("y")
    doc.root.elements[i].text = $host[ip].y
    i+=1
    doc.root.add_element("icon")
    doc.root.elements[i].text = $host[ip].icon
    i+=1
    doc.root.add_element("description")
    doc.root.elements[i].text = $host[ip].description
    i+=1
    doc.root.add_element("snmp_version")
    doc.root.elements[i].text = $host[ip].snmp_version
    i+=1
    doc.root.add_element("snmp_port")
    doc.root.elements[i].text = $host[ip].snmp_port
    i+=1
    doc.root.add_element("snmp_timeout")
    doc.root.elements[i].text = $host[ip].snmp_timeout
    i+=1
    doc.root.add_element("snmp_retry")
    doc.root.elements[i].text = $host[ip].snmp_retry
    i+=1
    doc.root.add_element("type")
    doc.root.elements[i].text = $host[ip].type
    i+=1
    doc.root.add_element("os")
    doc.root.elements[i].text = $host[ip].os
    i+=1

    doc.root.add_element("snmp_monitor")
    snmp_monitor=doc.root.elements[i]
    $host[ip].snmp_monitoring.each_value {|mon|
      snmp=Element.new("snmp")
      snmp.add_element("snmp_state")
      snmp.elements["snmp_state"].text = mon.get_state()
      snmp.add_element("oid_ref")
      snmp.elements["oid_ref"].text = mon.oidref
      snmp.add_element("snmp_oper")
      snmp.elements["snmp_oper"].text = SnmpMonitoring::TESTOP.index(mon.oper)
      snmp.add_element("snmp_threshold")
      snmp.elements["snmp_threshold"].text = mon.threshold.to_s()
      snmp.add_element("oid_sev")
      snmp.elements["oid_sev"].text = mon.raw_severity
      snmp_monitor.elements << snmp
    }
    i+=1

    doc.root.add_element("wmi_monitor")
    wmi_monitor=doc.root.elements[i]
    $host[ip].wmi_monitoring.each_value {|mon|
      wmi=Element.new("wmi")
      wmi.add_element("wmi_state")
      wmi.elements["wmi_state"].text = mon.get_state()
      wmi.add_element("wmi_ref")
      wmi.elements["wmi_ref"].text = mon.wmiref
      wmi.add_element("wmi_oper")
      wmi.elements["wmi_oper"].text = WmiMonitoring::TESTOP.index(mon.oper)
      wmi.add_element("wmi_value")
      wmi.elements["wmi_value"].text = mon.value.to_s()
      wmi.add_element("wmi_sev")
      wmi.elements["wmi_sev"].text = mon.raw_severity
      wmi_monitor.elements << wmi
    }
    i+=1

    doc.root.add_element("snmptrap_monitor")
    snmptrap_monitor=doc.root.elements[i]
    $host[ip].snmptrap_monitoring.each_value {|mon|
      snmptrap=Element.new("snmptrap")
      snmptrap.add_element("snmptrap_state")
      snmptrap.elements["snmptrap_state"].text = mon.get_state()
      snmptrap.add_element("snmptrap_ref")
      snmptrap.elements["snmptrap_ref"].text = mon.get_snmptrap_ref()
      snmptrap.add_element("trapsev")
      snmptrap.elements["trapsev"].text = mon.raw_severity
      snmptrap_monitor.elements << snmptrap
    }
    i+=1
  
    doc.root.add_element("custom_monitor")
    custom_monitor=doc.root.elements[i]
    $host[ip].custom_monitoring.each_value {|mon|
      custom=Element.new("custom")
      custom.add_element("custom_state")
      custom.elements["custom_state"].text = mon.get_state()
      custom.add_element("custom_name")
      custom.elements["custom_name"].text = mon.get_name()
      custom.add_element("custom_param")
      custom.elements["custom_param"].text = mon.get_param()
      custom.add_element("custom_sev")
      custom.elements["custom_sev"].text = mon.raw_severity
      custom.elements << custom
    }    
    i+=1

    doc.root.add_element("syslog_monitor")
    syslog_monitor=doc.root.elements[i]
    $host[ip].syslog_monitoring.each_value {|mon|
      syslog=Element.new("syslog")
      syslog.add_element("syslog_state")
      syslog.elements["syslog_state"].text = mon.get_state()
      syslog.add_element("syslog_ref")
      syslog.elements["syslog_ref"].text = mon.get_syslog_ref()
      syslog.add_element("syslog_sev")
      syslog.elements["syslog_sev"].text = mon.raw_severity
      syslog_monitor.elements << syslog
    }
    i+=1

    tf.puts(doc)
  }
  #all seems good
  tf.close
  FileUtils.move(tf.path, fic_name)
  set_unbusy()
end