summary refs log tree commit diff stats
path: root/lib/windows/nb30.nim
blob: 527e3a9e23a05a9ee8e1e9d17a40e17168bf3c9c (plain) (blame)
1
2
3
4
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
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
#
#
#            Nimrod's Runtime Library
#        (c) Copyright 2006 Andreas Rumpf
#
#    See the file "copying.txt", included in this
#    distribution, for details about the copyright.
#
#       NetBIOS 3.0 interface unit 

# This module contains the definitions for portable NetBIOS 3.0 support. 

{.deadCodeElim: on.}

import                        # Data structure templates 
  Windows

const 
  NCBNAMSZ* = 16              # absolute length of a net name
  MAX_LANA* = 254             # lana's in range 0 to MAX_LANA inclusive

type                          # Network Control Block
  PNCB* = ptr TNCB
  TNCBPostProc* = proc (P: PNCB)
  TNCB* {.final.} = object # Structure returned to the NCB command NCBASTAT is ADAPTER_STATUS followed
                           # by an array of NAME_BUFFER structures.
    ncb_command*: Char        # command code
    ncb_retcode*: Char        # return code
    ncb_lsn*: Char            # local session number
    ncb_num*: Char            # number of our network name
    ncb_buffer*: cstring      # address of message buffer
    ncb_length*: int16        # size of message buffer
    ncb_callname*: array[0..NCBNAMSZ - 1, char] # blank-padded name of remote
    ncb_name*: array[0..NCBNAMSZ - 1, char] # our blank-padded netname
    ncb_rto*: Char            # rcv timeout/retry count
    ncb_sto*: Char            # send timeout/sys timeout
    ncb_post*: TNCBPostProc   # POST routine address
    ncb_lana_num*: Char       # lana (adapter) number
    ncb_cmd_cplt*: Char       # 0xff => commmand pending
    ncb_reserve*: array[0..9, Char] # reserved, used by BIOS
    ncb_event*: THandle       # HANDLE to Win32 event which
                              # will be set to the signalled
                              # state when an ASYNCH command
                              # completes
  
  PAdapterStatus* = ptr TAdapterStatus
  TAdapterStatus* {.final.} = object 
    adapter_address*: array[0..5, Char]
    rev_major*: Char
    reserved0*: Char
    adapter_type*: Char
    rev_minor*: Char
    duration*: int16
    frmr_recv*: int16
    frmr_xmit*: int16
    iframe_recv_err*: int16
    xmit_aborts*: int16
    xmit_success*: DWORD
    recv_success*: DWORD
    iframe_xmit_err*: int16
    recv_buff_unavail*: int16
    t1_timeouts*: int16
    ti_timeouts*: int16
    reserved1*: DWORD
    free_ncbs*: int16
    max_cfg_ncbs*: int16
    max_ncbs*: int16
    xmit_buf_unavail*: int16
    max_dgram_size*: int16
    pending_sess*: int16
    max_cfg_sess*: int16
    max_sess*: int16
    max_sess_pkt_size*: int16
    name_count*: int16

  PNameBuffer* = ptr TNameBuffer
  TNameBuffer* {.final.} = object 
    name*: array[0..NCBNAMSZ - 1, Char]
    name_num*: Char
    name_flags*: Char


const                         # values for name_flags bits.
  NAME_FLAGS_MASK* = 0x00000087
  GROUP_NAME* = 0x00000080
  UNIQUE_NAME* = 0x00000000
  REGISTERING* = 0x00000000
  REGISTERED* = 0x00000004
  DEREGISTERED* = 0x00000005
  DUPLICATE* = 0x00000006
  DUPLICATE_DEREG* = 0x00000007

type # Structure returned to the NCB command NCBSSTAT is SESSION_HEADER followed
     # by an array of SESSION_BUFFER structures. If the NCB_NAME starts with an
     # asterisk then an array of these structures is returned containing the
     # status for all names.
  PSessionHeader* = ptr TSessionHeader
  TSessionHeader* {.final.} = object 
    sess_name*: Char
    num_sess*: Char
    rcv_dg_outstanding*: Char
    rcv_any_outstanding*: Char

  PSessionBuffer* = ptr TSessionBuffer
  TSessionBuffer* {.final.} = object 
    lsn*: Char
    state*: Char
    local_name*: array[0..NCBNAMSZ - 1, Char]
    remote_name*: array[0..NCBNAMSZ - 1, Char]
    rcvs_outstanding*: Char
    sends_outstanding*: Char


const                         # Values for state
  LISTEN_OUTSTANDING* = 0x00000001
  CALL_PENDING* = 0x00000002
  SESSION_ESTABLISHED* = 0x00000003
  HANGUP_PENDING* = 0x00000004
  HANGUP_COMPLETE* = 0x00000005
  SESSION_ABORTED* = 0x00000006

type # Structure returned to the NCB command NCBENUM.
     # On a system containing lana's 0, 2 and 3, a structure with
     # length =3, lana[0]=0, lana[1]=2 and lana[2]=3 will be returned.
  PLanaEnum* = ptr TLanaEnum
  TLanaEnum* {.final.} = object # Structure returned to the NCB command NCBFINDNAME is FIND_NAME_HEADER followed
                                # by an array of FIND_NAME_BUFFER structures.
    len*: Char                #  Number of valid entries in lana[]
    lana*: array[0..MAX_LANA, Char]

  PFindNameHeader* = ptr TFindNameHeader
  TFindNameHeader* {.final.} = object 
    node_count*: int16
    reserved*: Char
    unique_group*: Char

  PFindNameBuffer* = ptr TFindNameBuffer
  TFindNameBuffer* {.final.} = object # Structure provided with NCBACTION. The purpose of NCBACTION is to provide
                                      # transport specific extensions to netbios.
    len*: Char
    access_control*: Char
    frame_control*: Char
    destination_addr*: array[0..5, Char]
    source_addr*: array[0..5, Char]
    routing_info*: array[0..17, Char]

  PActionHeader* = ptr TActionHeader
  TActionHeader* {.final.} = object 
    transport_id*: int32
    action_code*: int16
    reserved*: int16


const                         # Values for transport_id
  ALL_TRANSPORTS* = "M\0\0\0"
  MS_NBF* = "MNBF"            # Special values and constants 

const                         # NCB Command codes
  NCBCALL* = 0x00000010       # NCB CALL
  NCBLISTEN* = 0x00000011     # NCB LISTEN
  NCBHANGUP* = 0x00000012     # NCB HANG UP
  NCBSEND* = 0x00000014       # NCB SEND
  NCBRECV* = 0x00000015       # NCB RECEIVE
  NCBRECVANY* = 0x00000016    # NCB RECEIVE ANY
  NCBCHAINSEND* = 0x00000017  # NCB CHAIN SEND
  NCBDGSEND* = 0x00000020     # NCB SEND DATAGRAM
  NCBDGRECV* = 0x00000021     # NCB RECEIVE DATAGRAM
  NCBDGSENDBC* = 0x00000022   # NCB SEND BROADCAST DATAGRAM
  NCBDGRECVBC* = 0x00000023   # NCB RECEIVE BROADCAST DATAGRAM
  NCBADDNAME* = 0x00000030    # NCB ADD NAME
  NCBDELNAME* = 0x00000031    # NCB DELETE NAME
  NCBRESET* = 0x00000032      # NCB RESET
  NCBASTAT* = 0x00000033      # NCB ADAPTER STATUS
  NCBSSTAT* = 0x00000034      # NCB SESSION STATUS
  NCBCANCEL* = 0x00000035     # NCB CANCEL
  NCBADDGRNAME* = 0x00000036  # NCB ADD GROUP NAME
  NCBENUM* = 0x00000037       # NCB ENUMERATE LANA NUMBERS
  NCBUNLINK* = 0x00000070     # NCB UNLINK
  NCBSENDNA* = 0x00000071     # NCB SEND NO ACK
  NCBCHAINSENDNA* = 0x00000072 # NCB CHAIN SEND NO ACK
  NCBLANSTALERT* = 0x00000073 # NCB LAN STATUS ALERT
  NCBACTION* = 0x00000077     # NCB ACTION
  NCBFINDNAME* = 0x00000078   # NCB FIND NAME
  NCBTRACE* = 0x00000079      # NCB TRACE
  ASYNCH* = 0x00000080        # high bit set = asynchronous
                              # NCB Return codes
  NRC_GOODRET* = 0x00000000   # good return
                              # also returned when ASYNCH request accepted
  NRC_BUFLEN* = 0x00000001    # illegal buffer length
  NRC_ILLCMD* = 0x00000003    # illegal command
  NRC_CMDTMO* = 0x00000005    # command timed out
  NRC_INCOMP* = 0x00000006    # message incomplete, issue another command
  NRC_BADDR* = 0x00000007     # illegal buffer address
  NRC_SNUMOUT* = 0x00000008   # session number out of range
  NRC_NORES* = 0x00000009     # no resource available
  NRC_SCLOSED* = 0x0000000A   # session closed
  NRC_CMDCAN* = 0x0000000B    # command cancelled
  NRC_DUPNAME* = 0x0000000D   # duplicate name
  NRC_NAMTFUL* = 0x0000000E   # name table full
  NRC_ACTSES* = 0x0000000F    # no deletions, name has active sessions
  NRC_LOCTFUL* = 0x00000011   # local session table full
  NRC_REMTFUL* = 0x00000012   # remote session table full
  NRC_ILLNN* = 0x00000013     # illegal name number
  NRC_NOCALL* = 0x00000014    # no callname
  NRC_NOWILD* = 0x00000015    # cannot put * in NCB_NAME
  NRC_INUSE* = 0x00000016     # name in use on remote adapter
  NRC_NAMERR* = 0x00000017    # name deleted
  NRC_SABORT* = 0x00000018    # session ended abnormally
  NRC_NAMCONF* = 0x00000019   # name conflict detected
  NRC_IFBUSY* = 0x00000021    # interface busy, IRET before retrying
  NRC_TOOMANY* = 0x00000022   # too many commands outstanding, retry later
  NRC_BRIDGE* = 0x00000023    # NCB_lana_num field invalid
  NRC_CANOCCR* = 0x00000024   # command completed while cancel occurring
  NRC_CANCEL* = 0x00000026    # command not valid to cancel
  NRC_DUPENV* = 0x00000030    # name defined by anther local process
  NRC_ENVNOTDEF* = 0x00000034 # environment undefined. RESET required
  NRC_OSRESNOTAV* = 0x00000035 # required OS resources exhausted
  NRC_MAXAPPS* = 0x00000036   # max number of applications exceeded
  NRC_NOSAPS* = 0x00000037    # no saps available for netbios
  NRC_NORESOURCES* = 0x00000038 # requested resources are not available
  NRC_INVADDRESS* = 0x00000039 # invalid ncb address or length > segment
  NRC_INVDDID* = 0x0000003B   # invalid NCB DDID
  NRC_LOCKFAIL* = 0x0000003C  # lock of user area failed
  NRC_OPENERR* = 0x0000003F   # NETBIOS not loaded
  NRC_SYSTEM* = 0x00000040    # system error
  NRC_PENDING* = 0x000000FF   # asynchronous command is not yet finished
                              # main user entry point for NetBIOS 3.0
                              #   Usage: Result = Netbios( pncb ); 

proc Netbios*(P: PNCB): Char{.stdcall, dynlib: "netapi32.dll", 
                              importc: "Netbios".}
# implementation
d2200; background-color: #fff0f0 } /* Literal.String */ .highlight .na { color: #336699 } /* Name.Attribute */ .highlight .nb { color: #003388 } /* Name.Builtin */ .highlight .nc { color: #bb0066; font-weight: bold } /* Name.Class */ .highlight .no { color: #003366; font-weight: bold } /* Name.Constant */ .highlight .nd { color: #555555 } /* Name.Decorator */ .highlight .ne { color: #bb0066; font-weight: bold } /* Name.Exception */ .highlight .nf { color: #0066bb; font-weight: bold } /* Name.Function */ .highlight .nl { color: #336699; font-style: italic } /* Name.Label */ .highlight .nn { color: #bb0066; font-weight: bold } /* Name.Namespace */ .highlight .py { color: #336699; font-weight: bold } /* Name.Property */ .highlight .nt { color: #bb0066; font-weight: bold } /* Name.Tag */ .highlight .nv { color: #336699 } /* Name.Variable */ .highlight .ow { color: #008800 } /* Operator.Word */ .highlight .w { color: #bbbbbb } /* Text.Whitespace */ .highlight .mb { color: #0000DD; font-weight: bold } /* Literal.Number.Bin */ .highlight .mf { color: #0000DD; font-weight: bold } /* Literal.Number.Float */ .highlight .mh { color: #0000DD; font-weight: bold } /* Literal.Number.Hex */ .highlight .mi { color: #0000DD; font-weight: bold } /* Literal.Number.Integer */ .highlight .mo { color: #0000DD; font-weight: bold } /* Literal.Number.Oct */ .highlight .sa { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Affix */ .highlight .sb { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Backtick */ .highlight .sc { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Char */ .highlight .dl { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Delimiter */ .highlight .sd { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Doc */ .highlight .s2 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Double */ .highlight .se { color: #0044dd; background-color: #fff0f0 } /* Literal.String.Escape */ .highlight .sh { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Heredoc */ .highlight .si { color: #3333bb; background-color: #fff0f0 } /* Literal.String.Interpol */ .highlight .sx { color: #22bb22; background-color: #f0fff0 } /* Literal.String.Other */ .highlight .sr { color: #008800; background-color: #fff0ff } /* Literal.String.Regex */ .highlight .s1 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Single */ .highlight .ss { color: #aa6600; background-color: #fff0f0 } /* Literal.String.Symbol */ .highlight .bp { color: #003388 } /* Name.Builtin.Pseudo */ .highlight .fm { color: #0066bb; font-weight: bold } /* Name.Function.Magic */ .highlight .vc { color: #336699 } /* Name.Variable.Class */ .highlight .vg { color: #dd7700 } /* Name.Variable.Global */ .highlight .vi { color: #3333bb } /* Name.Variable.Instance */ .highlight .vm { color: #336699 } /* Name.Variable.Magic */ .highlight .il { color: #0000DD; font-weight: bold } /* Literal.Number.Integer.Long */
#!/usr/bin/python
# coding=utf-8
#
# Copyright (C) 2009, 2010  Roman Zimbelmann <romanz@lavabit.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import os
import sys
import ranger

def parse_arguments():
	"""Parse the program arguments"""

	from optparse import OptionParser, SUPPRESS_HELP
	from ranger.ext.openstruct import OpenStruct
	from ranger import __version__, USAGE, DEFAULT_CONFDIR

	parser = OptionParser(usage=USAGE, version='ranger ' + __version__)

	parser.add_option('-d', '--debug', action='store_true',
			help="activate debug mode")
	parser.add_option('-c', '--clean', action='store_true',
			help="don't touch/require any config files. ")
	parser.add_option('-r', '--confdir', type='string',
			metavar='dir', default=DEFAULT_CONFDIR,
			help="the configuration directory. (%default)")
	parser.add_option('-m', '--mode', type='int', default=0, metavar='n',
			help="if a filename is supplied, run it with this mode")
	parser.add_option('-f', '--flags', type='string', default='',
			metavar='string',
			help="if a filename is supplied, run it with these flags.")

	options, positional = parser.parse_args()
	arg = OpenStruct(options.__dict__, targets=positional)
	arg.confdir = os.path.expanduser(arg.confdir)

	return arg


def load_settings(fm, clean):
	import ranger.api.commands
	if not clean:
		try:
			os.makedirs(ranger.arg.confdir)
		except OSError as err:
			if err.errno != 17:  # 17 means it already exists
				print("This configuration directory could not be created:")
				print(ranger.arg.confdir)
				print("To run ranger without the need for configuration")
				print("files, use the --clean option.")
				raise SystemExit()

		sys.path[0:0] = [ranger.arg.confdir]

		# Load commands
		comcont = ranger.api.commands.CommandContainer()
		ranger.api.commands.alias = comcont.alias
		try:
			import commands
			comcont.load_commands_from_module(commands)
		except ImportError:
			pass
		from ranger.defaults import commands
		comcont.load_commands_from_module(commands)
		commands = comcont

		# Load apps
		try:
			import apps
		except ImportError:
			from ranger.defaults import apps

		# Load keys
		from ranger import shared, api
		from ranger.api import keys
		keymanager = shared.EnvironmentAware.env.keymanager
		keys.keymanager = keymanager
		from ranger.defaults import keys
		try:
			import keys
		except ImportError:
			pass
		# COMPAT WARNING
		if hasattr(keys, 'initialize_commands'):
			print("Warning: the syntax for ~/.ranger/keys.py has changed.")
			print("Your custom keys are not loaded."\
					"  Please update your configuration.")
		del sys.path[0]
	else:
		comcont = ranger.api.commands.CommandContainer()
		ranger.api.commands.alias = comcont.alias
		from ranger.defaults import commands, keys, apps
		comcont.load_commands_from_module(commands)
		commands = comcont
	fm.commands = commands
	fm.keys = keys
	fm.apps = apps.CustomApplications()


def main():
	"""initialize objects and run the filemanager"""
	try:
		import curses
	except ImportError as errormessage:
		print(errormessage)
		print('ranger requires the python curses module. Aborting.')
		sys.exit(1)

	from signal import signal, SIGINT
	from locale import getdefaultlocale, setlocale, LC_ALL

	from ranger.ext import curses_interrupt_handler
	from ranger.core.fm import FM
	from ranger.core.environment import Environment
	from ranger.shared import (EnvironmentAware, FileManagerAware,
			SettingsAware)
	from ranger.gui.defaultui import DefaultUI as UI
	from ranger.fsobject.file import File

	# Ensure that a utf8 locale is set.
	if getdefaultlocale()[1] not in ('utf8', 'UTF-8'):
		for locale in ('en_US.utf8', 'en_US.UTF-8'):
			try: setlocale(LC_ALL, locale)
			except: pass
			else: break
		else: setlocale(LC_ALL, '')
	else: setlocale(LC_ALL, '')

	arg = parse_arguments()
	ranger.arg = arg

	if not ranger.arg.debug:
		curses_interrupt_handler.install_interrupt_handler()

	SettingsAware._setup()

	if arg.targets:
		target = arg.targets[0]
		if not os.access(target, os.F_OK):
			print("File or directory doesn't exist: %s" % target)
			sys.exit(1)
		elif os.path.isfile(target):
			thefile = File(target)
			fm = FM()
			load_settings(fm, ranger.arg.clean)
			fm.execute_file(thefile, mode=arg.mode, flags=arg.flags)
			sys.exit(0)
		else:
			path = target
	else:
		path = '.'

	try:
		# Initialize objects
		EnvironmentAware._assign(Environment(path))
		fm = FM()
		load_settings(fm, ranger.arg.clean)
		FileManagerAware._assign(fm)
		fm.ui = UI()

		# Run the file manager
		fm.initialize()
		fm.ui.initialize()
		fm.loop()
	finally:
		# Finish, clean up
		try:
			fm.ui.destroy()
		except (AttributeError, NameError):
			pass


if __name__ == '__main__':
	top_dir = os.path.dirname(sys.path[0])
	sys.path.insert(0, top_dir)
	main()