Class: Win32::Service

Inherits:
Object
  • Object
show all
Extended by:
Windows::Error, Windows::File, Windows::MSVCRT::Buffer, Windows::MSVCRT::String, Windows::Process, Windows::Security, Windows::Service
Includes:
Windows::Error, Windows::File, Windows::MSVCRT::Buffer, Windows::MSVCRT::String, Windows::Process, Windows::Security, Windows::Service
Defined in:
lib/win32/service.rb

Overview

The Service class encapsulates services controller actions, such as creating, starting, configuring or deleting services.

Defined Under Namespace

Classes: ConfigStruct, Error, ServiceStruct, StatusStruct

Constant Summary collapse

VERSION =

The version of the win32-service library

'0.7.2'
MANAGER_ALL_ACCESS =

Includes STANDARD_RIGHTS_REQUIRED, in addition to all other rights

SC_MANAGER_ALL_ACCESS
MANAGER_CREATE_SERVICE =

Required to call the CreateService function

SC_MANAGER_CREATE_SERVICE
MANAGER_CONNECT =

Required to connect to the service control manager.

SC_MANAGER_CONNECT
MANAGER_ENUMERATE_SERVICE =

Required to call the EnumServicesStatusEx function to list services

SC_MANAGER_ENUMERATE_SERVICE
MANAGER_LOCK =

Required to call the LockServiceDatabase function

SC_MANAGER_LOCK
MANAGER_MODIFY_BOOT_CONFIG =

Required to call the NotifyBootConfigStatus function

SC_MANAGER_MODIFY_BOOT_CONFIG
MANAGER_QUERY_LOCK_STATUS =

Required to call the QueryServiceLockStatus function

SC_MANAGER_QUERY_LOCK_STATUS
ALL_ACCESS =

Includes STANDARD_RIGHTS_REQUIRED in addition to all access rights

SERVICE_ALL_ACCESS
CHANGE_CONFIG =

Required to call functions that configure existing services

SERVICE_CHANGE_CONFIG
ENUMERATE_DEPENDENTS =

Required to enumerate all the services dependent on the service

SERVICE_ENUMERATE_DEPENDENTS
INTERROGATE =

Required to make a service report its status immediately

SERVICE_INTERROGATE
PAUSE_CONTINUE =

Required to control a service with a pause or resume

SERVICE_PAUSE_CONTINUE
QUERY_CONFIG =

Required to be able to gather configuration information about a service

SERVICE_QUERY_CONFIG
QUERY_STATUS =

Required to be ask the SCM about the status of a service

SERVICE_QUERY_STATUS
START =

Required to call the StartService function to start the service.

SERVICE_START
STOP =

Required to call the ControlService function to stop the service.

SERVICE_STOP
USER_DEFINED_CONTROL =

Required to call ControlService with a user defined control code

SERVICE_USER_DEFINED_CONTROL
KERNEL_DRIVER =

Driver service

SERVICE_KERNEL_DRIVER
FILE_SYSTEM_DRIVER =

File system driver service

SERVICE_FILE_SYSTEM_DRIVER
WIN32_OWN_PROCESS =

Service that runs in its own process

SERVICE_WIN32_OWN_PROCESS
WIN32_SHARE_PROCESS =

Service that shares a process with one or more other services.

SERVICE_WIN32_SHARE_PROCESS
INTERACTIVE_PROCESS =

The service can interact with the desktop

SERVICE_INTERACTIVE_PROCESS
DRIVER =
SERVICE_DRIVER
TYPE_ALL =
SERVICE_TYPE_ALL
BOOT_START =

A service started automatically by the SCM during system startup

SERVICE_BOOT_START
SYSTEM_START =

A device driver started by the IoInitSystem function. Drivers only

SERVICE_SYSTEM_START
AUTO_START =

A service started automatically by the SCM during system startup

SERVICE_AUTO_START
DEMAND_START =

A service started by the SCM when a process calls StartService

SERVICE_DEMAND_START
DISABLED =

A service that cannot be started

SERVICE_DISABLED
ERROR_IGNORE =

Error logged, startup continues

SERVICE_ERROR_IGNORE
ERROR_NORMAL =

Error logged, pop up message, startup continues

SERVICE_ERROR_NORMAL
ERROR_SEVERE =

Error logged, startup continues, system restarted last known good config

SERVICE_ERROR_SEVERE
ERROR_CRITICAL =

Error logged, startup fails, system restarted last known good config

SERVICE_ERROR_CRITICAL
STOPPED =

Service is not running

SERVICE_STOPPED
START_PENDING =

Service has received a start signal but is not yet running

SERVICE_START_PENDING
STOP_PENDING =

Service has received a stop signal but is not yet stopped

SERVICE_STOP_PENDING
RUNNING =

Service is running

SERVICE_RUNNING
CONTINUE_PENDING =

Service has received a signal to resume but is not yet running

SERVICE_CONTINUE_PENDING
PAUSE_PENDING =

Service has received a signal to pause but is not yet paused

SERVICE_PAUSE_PENDING
PAUSED =

Service is paused

SERVICE_PAUSED
CONTROL_STOP =

Notifies service that it should stop

SERVICE_CONTROL_STOP
CONTROL_PAUSE =

Notifies service that it should pause

SERVICE_CONTROL_PAUSE
CONTROL_CONTINUE =

Notifies service that it should resume

SERVICE_CONTROL_CONTINUE
CONTROL_INTERROGATE =

Notifies service that it should return its current status information

SERVICE_CONTROL_INTERROGATE
CONTROL_PARAMCHANGE =

Notifies a service that its parameters have changed

SERVICE_CONTROL_PARAMCHANGE
CONTROL_NETBINDADD =

Notifies a service that there is a new component for binding

SERVICE_CONTROL_NETBINDADD
CONTROL_NETBINDREMOVE =

Notifies a service that a component for binding has been removed

SERVICE_CONTROL_NETBINDREMOVE
CONTROL_NETBINDENABLE =

Notifies a service that a component for binding has been enabled

SERVICE_CONTROL_NETBINDENABLE
CONTROL_NETBINDDISABLE =

Notifies a service that a component for binding has been disabled

SERVICE_CONTROL_NETBINDDISABLE
ACTION_NONE =

No action

SC_ACTION_NONE
ACTION_REBOOT =

Reboot the computer

SC_ACTION_REBOOT
ACTION_RESTART =

Restart the service

SC_ACTION_RESTART
ACTION_RUN_COMMAND =

Run a command

SC_ACTION_RUN_COMMAND

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Service

Creates a new service with the specified options. A service_name must be specified or an ArgumentError is raised. A host option may be specified. If no host is specified the local machine is used.

Possible Options:

  • service_name => nil (you must specify)

  • host => nil (optional)

  • display_name => service_name

  • desired_access => Service::ALL_ACCESS

  • service_type => Service::WIN32_OWN_PROCESS |

    Service::INTERACTIVE_PROCESS
    
  • start_type => Service::DEMAND_START

  • error_control => Service::ERROR_NORMAL

  • binary_path_name => nil

  • load_order_group => nil

  • dependencies => nil

  • service_start_name => nil

  • password => nil

  • description => nil

  • failure_reset_period => nil,

  • failure_reboot_message => nil,

  • failure_command => nil,

  • failure_actions => nil,

  • failure_delay => 0

Example:

# Configure everything
Service.new(
  :service_name       => 'some_service',
  :host               => 'localhost',
  :service_type       => Service::WIN32_OWN_PROCESS,
  :description        => 'A custom service I wrote just for fun',
  :start_type         => Service::AUTO_START,
  :error_control      => Service::ERROR_NORMAL,
  :binary_path_name   => 'C:\path\to\some_service.exe',
  :load_order_group   => 'Network',
  :dependencies       => ['W32Time','Schedule'],
  :service_start_name => 'SomeDomain\\User',
  :password           => 'XXXXXXX',
  :display_name       => 'This is some service',
)

Raises:

  • (TypeError)


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
# File 'lib/win32/service.rb', line 314

def initialize(options={})        
  unless options.is_a?(Hash)
    raise ArgumentError, 'options parameter must be a hash'
  end

  if options.empty?
    raise ArgumentError, 'no options provided'
  end

  opts = {
    'display_name'           => nil,
    'desired_access'         => SERVICE_ALL_ACCESS,
    'service_type'           => SERVICE_WIN32_OWN_PROCESS |
                                SERVICE_INTERACTIVE_PROCESS,
    'start_type'             => SERVICE_DEMAND_START,
    'error_control'          => SERVICE_ERROR_NORMAL,
    'binary_path_name'       => nil,
    'load_order_group'       => nil,
    'dependencies'           => nil,
    'service_start_name'     => nil,
    'password'               => nil,
    'description'            => nil,
    'failure_reset_period'   => nil,
    'failure_reboot_message' => nil,
    'failure_command'        => nil,
    'failure_actions'        => nil,
    'failure_delay'          => 0,
    'host'                   => nil,
    'service_name'           => nil            
  }

  # Validate the hash options
  options.each{ |key, value|
    key = key.to_s.downcase
    unless opts.include?(key)
      raise ArgumentError, "Invalid option '#{key}'"
    end
    opts[key] = value
  }
     
  unless opts['service_name']
    raise ArgumentError, 'No service_name specified'            
  end
     
  service_name = opts.delete('service_name')
  host = opts.delete('host')
     
  raise TypeError unless service_name.is_a?(String)
  raise TypeError if host && !host.is_a?(String)

  begin
    handle_scm = OpenSCManager(host, 0, SC_MANAGER_CREATE_SERVICE)

    if handle_scm == 0
      raise Error, get_last_error
    end
    
    # Display name defaults to service_name
    opts['display_name'] ||= service_name

    dependencies = opts['dependencies']

    if dependencies && !dependencies.empty?
      unless dependencies.is_a?(Array) || dependencies.is_a?(String)
        raise TypeError, 'dependencies must be a string or array'
      end
       
      if dependencies.is_a?(Array)
        dependencies = dependencies.join("\000")
      end
          
      dependencies += "\000"
    end

    handle_scs = CreateService(
      handle_scm,
      service_name,
      opts['display_name'],
      opts['desired_access'],
      opts['service_type'],
      opts['start_type'],
      opts['error_control'],
      opts['binary_path_name'],
      opts['load_order_group'],
      0,
      dependencies,
      opts['service_start_name'],
      opts['password']
    )

    if handle_scs == 0
      raise Error, get_last_error
    end

    if opts['description']
      description = 0.chr * 4 # sizeof(SERVICE_DESCRIPTION)
      description[0,4] = [opts['description']].pack('p*')

      bool = ChangeServiceConfig2(
        handle_scs,
        SERVICE_CONFIG_DESCRIPTION,
        description
      )

      unless bool
        raise Error, get_last_error
      end
    end
     
    if opts['failure_reset_period'] || opts['failure_reboot_message'] ||
       opts['failure_command'] || opts['failure_actions']
    then
      Service.configure_failure_actions(handle_scs, opts)
    end         
  ensure
    CloseServiceHandle(handle_scs) if handle_scs && handle_scs > 0
    CloseServiceHandle(handle_scm) if handle_scm && handle_scm > 0
  end

  self
end

Class Method Details

.config_info(service, host = nil) ⇒ Object

Returns a ServiceConfigInfo struct containing the configuration information about service on host, or the local host if no host is specified.

Example:

Service.config_info('W32Time') => <struct ServiceConfigInfo ...>

– This contains less information that the ServiceInfo struct that is returned with the Service.services method, but is faster for looking up basic information for a single service.

Raises:

  • (TypeError)


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
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
# File 'lib/win32/service.rb', line 869

def self.config_info(service, host=nil)
  raise TypeError if host && !host.is_a?(String)

  handle_scm = OpenSCManager(host, nil, SC_MANAGER_ENUMERATE_SERVICE)

  if handle_scm == 0
    raise Error, get_last_error
  end

  begin
    handle_scs = OpenService(handle_scm, service, SERVICE_QUERY_CONFIG)

    if handle_scs == 0
      raise Error, get_last_error
    end

    # First, get the buf size needed
    bytes_needed = [0].pack('L')

    bool = QueryServiceConfig(handle_scs, nil, 0, bytes_needed)

    if !bool && GetLastError() != ERROR_INSUFFICIENT_BUFFER
      raise Error, get_last_error
    end

    buf = 0.chr * bytes_needed.unpack('L')[0]
    bytes = [0].pack('L')

    bool = QueryServiceConfig(handle_scs, buf, buf.size, bytes_needed)

    unless bool
      raise Error, get_last_error
    end
  ensure
    CloseServiceHandle(handle_scs) if handle_scs && handle_scs > 0
    CloseServiceHandle(handle_scm)
  end

  binary_path_name   = 0.chr * 1024
  load_order_group   = 0.chr * 1024
  dependencies       = 0.chr * 1024
  service_start_name = 0.chr * 260
  display_name       = 0.chr * 260

  strcpy(binary_path_name, buf[12,4].unpack('L')[0])
  binary_path_name = binary_path_name.unpack('Z*')[0]

  strcpy(load_order_group, buf[16,4].unpack('L')[0])
  load_order_group = load_order_group.unpack('Z*')[0]

  dependencies = get_dependencies(buf[24,4].unpack('L').first)

  strcpy(service_start_name, buf[28,4].unpack('L')[0])
  service_start_name = service_start_name.unpack('Z*')[0]

  strcpy(display_name, buf[32,4].unpack('L')[0])
  display_name = display_name.unpack('Z*')[0]

  ConfigStruct.new(
    get_service_type(buf[0,4].unpack('L')[0]),
    get_start_type(buf[4,4].unpack('L')[0]),
    get_error_control(buf[8,4].unpack('L')[0]),
    binary_path_name,
    load_order_group,
    buf[20,4].unpack('L')[0],
    dependencies,
    service_start_name,
    display_name
  )
end

.configure(options = {}) ⇒ Object

Configures the named service on host, or the local host if no host is specified. The options parameter is a hash that can contain any of the following parameters:

  • service_type

  • start_type

  • error_control

  • binary_path_name

  • load_order_group

  • dependencies

  • service_start_name

  • password (used with service_start_name)

  • display_name

  • description

  • failure_reset_period

  • failure_reboot_message

  • failure_command

  • failure_actions

  • failure_delay

Examples:

# Configure only the display name
Service.configure(
  :service_name => 'some_service',
  :display_name => 'Test 33'
)

# Configure everything
Service.configure(
   :service_name       => 'some_service'
   :service_type       => Service::WIN32_OWN_PROCESS,
   :start_type         => Service::AUTO_START,
   :error_control      => Service::ERROR_NORMAL,
   :binary_path_name   => 'C:\path\to\some_service.exe',
   :load_order_group   => 'Network',
   :dependencies       => ['W32Time','Schedule']
   :service_start_name => 'SomeDomain\\User',
   :password           => 'XXXXXXX',
   :display_name       => 'This is some service',
   :description        => 'A custom service I wrote just for fun'
)

Raises:

  • (TypeError)


479
480
481
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
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
# File 'lib/win32/service.rb', line 479

def self.configure(options={})    
  unless options.is_a?(Hash)
    raise ArgumentError, 'options parameter must be a hash'
  end

  if options.empty?
    raise ArgumentError, 'no options provided'
  end

  opts = {
    'service_type'           => SERVICE_NO_CHANGE,
    'start_type'             => SERVICE_NO_CHANGE,
    'error_control'          => SERVICE_NO_CHANGE,
    'binary_path_name'       => nil,
    'load_order_group'       => nil,
    'dependencies'           => nil,
    'service_start_name'     => nil,
    'password'               => nil,
    'display_name'           => nil,
    'description'            => nil,
    'failure_reset_period'   => nil,
    'failure_reboot_message' => nil,
    'failure_command'        => nil,
    'failure_actions'        => nil,
    'failure_delay'          => 0,
    'service_name'           => nil,
    'host'                   => nil
  }

  # Validate the hash options
  options.each{ |key, value|
    key = key.to_s.downcase
    unless opts.include?(key)
      raise ArgumentError, "Invalid option '#{key}'"
    end
    opts[key] = value
  }
     
  unless opts['service_name']
    raise ArgumentError, 'No service_name specified'            
  end
     
  service = opts.delete('service_name')
  host = opts.delete('host')

  raise TypeError unless service.is_a?(String)
  raise TypeError unless host.is_a?(String) if host

  begin
    handle_scm = OpenSCManager(host, 0, SC_MANAGER_CONNECT)

    if handle_scm == 0
      raise Error, get_last_error
    end
     
    desired_access = SERVICE_CHANGE_CONFIG
     
    if opts['failure_actions']
      desired_access |= SERVICE_START
    end

    handle_scs = OpenService(
      handle_scm,
      service,
      desired_access
    )

    if handle_scs == 0
      raise Error, get_last_error
    end

    dependencies = opts['dependencies']

    if dependencies && !dependencies.empty?
      unless dependencies.is_a?(Array) || dependencies.is_a?(String)
        raise TypeError, 'dependencies must be a string or array'
      end

      if dependencies.is_a?(Array)
        dependencies = dependencies.join("\000")
      end
        
      dependencies += "\000"
    end

    bool = ChangeServiceConfig(
      handle_scs,
      opts['service_type'],
      opts['start_type'],
      opts['error_control'],
      opts['binary_path_name'],
      opts['load_order_group'],
      0,
      dependencies,
      opts['service_start_name'],
      opts['password'],
      opts['display_name']
    )

    unless bool
      raise Error, get_last_error
    end

    if opts['description']
      description = 0.chr * 4 # sizeof(SERVICE_DESCRIPTION)
      description[0,4] = [opts['description']].pack('p*')

      bool = ChangeServiceConfig2(
        handle_scs,
        SERVICE_CONFIG_DESCRIPTION,
        description
      )

      unless bool
        raise Error, get_last_error
      end
    end

    if opts['failure_reset_period'] || opts['failure_reboot_message'] ||
       opts['failure_command'] || opts['failure_actions']
    then
      configure_failure_actions(handle_scs, opts)
    end
  ensure
    CloseServiceHandle(handle_scs) if handle_scs && handle_scs > 0
    CloseServiceHandle(handle_scm) if handle_scm && handle_scm > 0
  end

  self
end

.delete(service, host = nil) ⇒ Object

Deletes the specified service from host, or the local host if no host is specified. Returns self.

Technical note. This method is not instantaneous. The service is first marked for deletion from the service control manager database. Then all handles to the service are closed. Then an attempt to stop the service is made. If the service cannot be stopped, the service control manager database entry is removed when the system is restarted.

Example:

Service.delete('SomeService') => self


832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
# File 'lib/win32/service.rb', line 832

def self.delete(service, host=nil)
  handle_scm = OpenSCManager(host, 0, SC_MANAGER_CREATE_SERVICE)
   
  if handle_scm == 0
    raise Error, get_last_error
  end
   
  begin
    handle_scs = OpenService(handle_scm, service, DELETE)

    if handle_scs == 0
      raise Error, get_last_error
    end
   
    unless DeleteService(handle_scs)
      raise Error, get_last_error
    end
  ensure
    CloseServiceHandle(handle_scs) if handle_scs && handle_scs > 0
    CloseServiceHandle(handle_scm)
  end

  self
end

.exists?(service, host = nil) ⇒ Boolean

Returns whether or not service exists on host or localhost, if no host is specified.

Example:

Service.exists?(‘W32Time’) => true

Returns:

  • (Boolean)


617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
# File 'lib/win32/service.rb', line 617

def self.exists?(service, host=nil)
  bool = false

  begin
    handle_scm = OpenSCManager(host, 0, SC_MANAGER_ENUMERATE_SERVICE)
     
    if handle_scm == 0
      raise Error, get_last_error
    end
     
    handle_scs = OpenService(handle_scm, service, SERVICE_QUERY_STATUS)
    bool = true if handle_scs > 0
  ensure
    CloseServiceHandle(handle_scm) if handle_scm && handle_scm > 0
    CloseServiceHandle(handle_scs) if handle_scs && handle_scs > 0
  end

  bool         
end

.get_display_name(service, host = nil) ⇒ Object Also known as: getdisplayname

Returns the display name of the specified service name, i.e. the string displayed in the Services GUI. Raises a Service::Error if the service name cannot be found.

If a host is provided, the information will be retrieved from that host. Otherwise, the information is pulled from the local host (the default behavior).

Example:

Service.get_display_name(‘W32Time’) => ‘Windows Time’



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
# File 'lib/win32/service.rb', line 649

def self.get_display_name(service, host=nil)
  handle_scm = OpenSCManager(host, 0, SC_MANAGER_CONNECT)
    
  if handle_scm == 0
    raise Error, get_last_error
  end
     
  display_name = 0.chr * 260
  display_buf  = [display_name.size].pack('L')

  begin
    bool = GetServiceDisplayName(
      handle_scm,
      service,
      display_name,
      display_buf
    )

    unless bool
      raise Error, get_last_error
    end
  ensure
    CloseServiceHandle(handle_scm)
  end

  display_name.unpack('Z*')[0]
end

.get_service_name(display_name, host = nil) ⇒ Object Also known as: getservicename

Returns the service name of the specified service from the provided display_name. Raises a Service::Error if the display_name cannote be found.

If a host is provided, the information will be retrieved from that host. Otherwise, the information is pulled from the local host (the default behavior).

Example:

Service.get_service_name(‘Windows Time’) => ‘W32Time’



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
# File 'lib/win32/service.rb', line 689

def self.get_service_name(display_name, host=nil)
  handle_scm = OpenSCManager(host, 0, SC_MANAGER_CONNECT)
   
  if handle_scm == 0
    raise Error, get_last_error
  end
     
  service_name = 0.chr * 260
  service_buf  = [service_name.size].pack('L')
     
  begin
    bool = GetServiceKeyName(
      handle_scm,
      display_name,
      service_name,
      service_buf
    )

    unless bool
      raise Error, get_last_error
    end
  ensure
    CloseServiceHandle(handle_scm)
  end

  service_name.unpack('Z*')[0]
end

.pause(service, host = nil) ⇒ Object

Pauses the given service on host, or the local host if no host is specified. Returns self

Note that pausing a service that is already paused will have no effect and it will not raise an error.

Be aware that not all services are configured to accept a pause command. Attempting to pause a service that isn’t setup to receive a pause command will raise an error.

Example:

Service.pause('Schedule') => self


795
796
797
798
799
800
# File 'lib/win32/service.rb', line 795

def self.pause(service, host=nil)
  service_signal = SERVICE_PAUSE_CONTINUE
  control_signal = SERVICE_CONTROL_PAUSE
  send_signal(service, host, service_signal, control_signal)
  self
end

.resume(service, host = nil) ⇒ Object

Resume the given service on host, or the local host if no host is specified. Returns self.

Note that resuming a service that’s already running will have no effect and it will not raise an error.

Example:

Service.resume('Schedule') => self


812
813
814
815
816
817
# File 'lib/win32/service.rb', line 812

def self.resume(service, host=nil)
  service_signal = SERVICE_PAUSE_CONTINUE
  control_signal = SERVICE_CONTROL_CONTINUE
  send_signal(service, host, service_signal, control_signal)
  self
end

.services(host = nil, group = nil) ⇒ Object

Enumerates over a list of service types on host, or the local machine if no host is specified, yielding a ServiceInfo struct for each service.

If a group is specified, then only those services that belong to that load order group are enumerated. If an empty string is provided, then only services that do not belong to any group are enumerated. If this parameter is nil (the default), group membership is ignored and all services are enumerated. This value is not case sensitive.

Examples:

# Enumerate over all services on the localhost
Service.services{ |service| p service }

# Enumerate over all services on a remote host
Service.services('some_host'){ |service| p service }

# Enumerate over all 'network' services locally
Service.services(nil, 'network'){ |service| p service }


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
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
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
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
# File 'lib/win32/service.rb', line 1034

def self.services(host=nil, group=nil)
  unless host.nil?
    raise TypeError unless host.is_a?(String) # Avoid strange errors
  end
     
  unless group.nil?
    raise TypeError unless group.is_a?(String) # Avoid strange errors
  end
                   
  handle_scm = OpenSCManager(host, 0, SC_MANAGER_ENUMERATE_SERVICE)
     
  if handle_scm == 0
    raise Error, get_last_error
  end
      
  bytes_needed      = [0].pack('L')
  services_returned = [0].pack('L')
  resume_handle     = [0].pack('L')

  begin
    # The first call is used to determine the required buffer size
    bool = EnumServicesStatusEx(
      handle_scm,
      SC_ENUM_PROCESS_INFO,
      SERVICE_WIN32 | SERVICE_DRIVER,
      SERVICE_STATE_ALL,
      0,
      0,
      bytes_needed,
      services_returned,
      resume_handle,
      group
    )

    err_num = GetLastError()

    if !bool && err_num == ERROR_MORE_DATA
      service_buf = 0.chr * bytes_needed.unpack('L').first
    else
      raise Error, get_last_error(err_num)
    end
      
    bool = EnumServicesStatusEx(
      handle_scm,
      SC_ENUM_PROCESS_INFO,
      SERVICE_WIN32 | SERVICE_DRIVER,
      SERVICE_STATE_ALL,
      service_buf,
      service_buf.size,
      bytes_needed,
      services_returned,
      resume_handle,
      group
    )
     
    unless bool
      raise Error, get_last_error
    end

    num_services = services_returned.unpack('L').first
       
    index = 0
    services_array = [] unless block_given?

    1.upto(num_services){ |num|
      service_name = 0.chr * 260
      display_name = 0.chr * 260

      info = service_buf[index, 44] # sizeof(SERVICE_STATUS_PROCESS)

      strcpy(service_name, info[0,4].unpack('L').first)
      strcpy(display_name, info[4,4].unpack('L').first)

      service_name = service_name.unpack('Z*')[0]
      display_name = display_name.unpack('Z*')[0]
         
      dw_service_type = info[8,4].unpack('L').first
   
      service_type  = get_service_type(dw_service_type)
      current_state = get_current_state(info[12,4].unpack('L').first)
      controls      = get_controls_accepted(info[16,4].unpack('L').first)
      interactive   = dw_service_type & SERVICE_INTERACTIVE_PROCESS > 0
      win_exit_code = info[20,4].unpack('L').first
      ser_exit_code = info[24,4].unpack('L').first
      check_point   = info[28,4].unpack('L').first
      wait_hint     = info[32,4].unpack('L').first
      pid           = info[36,4].unpack('L').first
      service_flags = info[40,4].unpack('L').first

      begin
        handle_scs = OpenService(
          handle_scm,
          service_name,
          SERVICE_QUERY_CONFIG
        )
           
        if handle_scs == 0
          raise Error, get_last_error
        end

        config_buf = get_config_info(handle_scs)

        if config_buf != ERROR_FILE_NOT_FOUND
          binary_path = 0.chr * 1024
          strcpy(binary_path, config_buf[12,4].unpack('L').first)
          binary_path = binary_path.unpack('Z*')[0]

          load_order = 0.chr * 1024
          strcpy(load_order, config_buf[16,4].unpack('L').first)
          load_order = load_order.unpack('Z*')[0]
       
          start_name = 0.chr * 1024
          strcpy(start_name, config_buf[28,4].unpack('L').first)
          start_name = start_name.unpack('Z*')[0]
        
          start_type = get_start_type(config_buf[4,4].unpack('L').first)
          error_ctrl = get_error_control(config_buf[8,4].unpack('L').first)

          tag_id = config_buf[20,4].unpack('L').first

          deps = get_dependencies(config_buf[24,4].unpack('L').first)

          description = 0.chr * 2048
          buf = get_config2_info(handle_scs, SERVICE_CONFIG_DESCRIPTION) 

          strcpy(description, buf[0,4].unpack('L').first)
          description = description.unpack('Z*')[0]
        else
          msg = "WARNING: The registry entry for the #{service_name} "
          msg += "service could not be found."
          warn msg
         
          binary_path = nil
          load_order  = nil
          start_name  = nil
          start_type  = nil
          error_ctrl  = nil
          tag_id      = nil
          deps        = nil
          description = nil
        end
        
        buf2 = get_config2_info(handle_scs, SERVICE_CONFIG_FAILURE_ACTIONS)
        
        if buf2 != ERROR_FILE_NOT_FOUND
          reset_period = buf2[0,4].unpack('L').first
        
          reboot_msg = 0.chr * 260
          strcpy(reboot_msg, buf2[4,4].unpack('L').first)
          reboot_msg = reboot_msg.unpack('Z*')[0]
        
          command = 0.chr * 260
          strcpy(command, buf2[8,4].unpack('L').first)
          command = command.unpack('Z*')[0]
        
          num_actions = buf2[12,4].unpack('L').first
          actions = nil
        
          if num_actions > 0
            action_ptr = buf2[16,4].unpack('L').first
            action_buf = [0,0].pack('LL') * num_actions
            memcpy(action_buf, action_ptr, action_buf.size)
           
            i = 0
            actions = {}
            num_actions.times{ |n|
              action_type, delay = action_buf[i, 8].unpack('LL')
              action_type = get_action_type(action_type)
              actions[n+1] = {:action_type => action_type, :delay => delay}
              i += 8
            }
          end
        else
          reset_period   = nil
          reboot_message = nil
          command        = nil
          actions        = nil
        end
      ensure
        CloseServiceHandle(handle_scs) if handle_scs > 0
      end
      
      struct = ServiceStruct.new(
        service_name,
        display_name,
        service_type,
        current_state,
        controls,
        win_exit_code,
        ser_exit_code,
        check_point,
        wait_hint,
        binary_path,
        start_type,
        error_ctrl,
        load_order,
        tag_id,
        start_name,
        deps,
        description,
        interactive,
        pid,
        service_flags,
        reset_period,
        reboot_msg,
        command,
        num_actions,
        actions
      )
      
      if block_given?
         yield struct
      else
         services_array << struct
      end

      index += 44 # sizeof(SERVICE_STATUS_PROCESS)
    }
  ensure
    CloseServiceHandle(handle_scm)
  end
   
  block_given? ? nil : services_array
end

.start(service, host = nil, *args) ⇒ Object

Attempts to start the named service on host, or the local machine if no host is provided. If args are provided, they are passed to the Daemon#service_main method.

Examples:

# Start 'SomeSvc' on the local machine
Service.start('SomeSvc', nil) => self

# Start 'SomeSvc' on host 'foo', passing 'hello' as an argument
Service.start('SomeSvc', 'foo', 'hello') => self


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
# File 'lib/win32/service.rb', line 729

def self.start(service, host=nil, *args)
  handle_scm = OpenSCManager(host, nil, SC_MANAGER_CONNECT)

  if handle_scm == 0
   raise Error, get_last_error
  end
     
  begin
    handle_scs = OpenService(handle_scm, service, SERVICE_START)
              
    if handle_scs == 0
      raise Error, get_last_error
    end
       
    num_args = 0
     
    if args.empty?
      args = nil
    else
      num_args = args.length
      args = args.map{ |x| [x].pack('p*') }.join
    end     
       
    unless StartService(handle_scs, num_args, args)
      raise Error, get_last_error
    end
       
  ensure
    CloseServiceHandle(handle_scs) if handle_scs && handle_scs > 0
    CloseServiceHandle(handle_scm)
  end
    
  self                          
end

.status(service, host = nil) ⇒ Object

Returns a ServiceStatus struct indicating the status of service name on host, or the localhost if none is provided.

Example:

Service.status(‘W32Time’) => <struct Struct::ServiceStatus …>



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
1009
1010
1011
# File 'lib/win32/service.rb', line 947

def self.status(service, host=nil)
  handle_scm = OpenSCManager(host, 0, SC_MANAGER_ENUMERATE_SERVICE)
      
  if handle_scm == 0
    raise Error, get_last_error
  end
       
  begin
    handle_scs = OpenService(
      handle_scm,
      service,
      SERVICE_QUERY_STATUS
    )
       
    if handle_scs == 0
      raise Error, get_last_error
    end
       
    # SERVICE_STATUS_PROCESS struct
    status = [0,0,0,0,0,0,0,0,0].pack('LLLLLLLLL')
    bytes  = [0].pack('L')
       
    bool = QueryServiceStatusEx(
      handle_scs,
      SC_STATUS_PROCESS_INFO,
      status,
      status.size,
      bytes
    )
       
    unless bool
      raise Error, get_last_error
    end
       
    dw_service_type = status[0,4].unpack('L').first
       
    service_type  = get_service_type(dw_service_type)
    current_state = get_current_state(status[4,4].unpack('L').first)
    controls      = get_controls_accepted(status[8,4].unpack('L').first)
    interactive   = dw_service_type & SERVICE_INTERACTIVE_PROCESS > 0
       
    # Note that the pid and service flags will always return 0 if you're
    # on Windows NT 4 or using a version of Ruby compiled with VC++ 6
    # or earlier.
    # 
    status_struct = StatusStruct.new(
      service_type,
      current_state,
      controls,
      status[12,4].unpack('L').first, # Win32ExitCode
      status[16,4].unpack('L').first, # ServiceSpecificExitCode
      status[20,4].unpack('L').first, # CheckPoint
      status[24,4].unpack('L').first, # WaitHint
      interactive,
      status[28,4].unpack('L').first, # ProcessId
      status[32,4].unpack('L').first  # ServiceFlags
    )
       
  ensure
    CloseServiceHandle(handle_scs) if handle_scs && handle_scs > 0
    CloseServiceHandle(handle_scm)
  end
   
  status_struct
end

.stop(service, host = nil) ⇒ Object

Stops a the given service on host, or the local host if no host is specified. Returns self.

Note that attempting to stop an already stopped service raises Service::Error.

Example:

Service.stop('W32Time') => self


774
775
776
777
778
779
# File 'lib/win32/service.rb', line 774

def self.stop(service, host=nil)
  service_signal = SERVICE_STOP
  control_signal = SERVICE_CONTROL_STOP
  send_signal(service, host, service_signal, control_signal)
  self
end