codekingpro commited on
Commit
7235b12
·
verified ·
1 Parent(s): 19cfe89

Add files using upload-large-folder tool

Browse files
Files changed (50) hide show
  1. bin/api_call.py +219 -0
  2. bin/big_file_sender.py +78 -0
  3. bin/msbuild.bat +2 -0
  4. bin/rag_system.py +174 -0
  5. cuda_toolkit/version.json +118 -0
  6. git/usr/share/perl5/core_perl/I18N/LangTags.pm +887 -0
  7. git/usr/share/perl5/core_perl/IO/Compress.pm +27 -0
  8. git/usr/share/perl5/core_perl/IO/Zlib.pm +740 -0
  9. git/usr/share/perl5/core_perl/IPC/Cmd.pm +2187 -0
  10. git/usr/share/perl5/core_perl/IPC/Open2.pm +173 -0
  11. git/usr/share/perl5/core_perl/IPC/Open3.pm +507 -0
  12. git/usr/share/perl5/core_perl/JSON/PP.pm +0 -0
  13. git/usr/share/perl5/core_perl/Math/BigFloat.pm +0 -0
  14. git/usr/share/perl5/core_perl/Math/BigInt.pm +0 -0
  15. git/usr/share/perl5/core_perl/Math/BigRat.pm +0 -0
  16. git/usr/share/perl5/core_perl/Math/Complex.pm +2138 -0
  17. git/usr/share/perl5/core_perl/Math/Trig.pm +773 -0
  18. git/usr/share/perl5/core_perl/Memoize/AnyDBM_File.pm +37 -0
  19. git/usr/share/perl5/core_perl/Memoize/Expire.pm +352 -0
  20. git/usr/share/perl5/core_perl/Memoize/NDBM_File.pm +39 -0
  21. git/usr/share/perl5/core_perl/Memoize/SDBM_File.pm +27 -0
  22. git/usr/share/perl5/core_perl/Memoize/Storable.pm +75 -0
  23. git/usr/share/perl5/core_perl/Module/CoreList.pm +0 -0
  24. git/usr/share/perl5/core_perl/Module/Load.pm +373 -0
  25. git/usr/share/perl5/core_perl/Module/Loaded.pm +142 -0
  26. git/usr/share/perl5/core_perl/Module/Metadata.pm +1207 -0
  27. git/usr/share/perl5/core_perl/Net/Cmd.pm +910 -0
  28. git/usr/share/perl5/core_perl/Net/Config.pm +381 -0
  29. git/usr/share/perl5/core_perl/Net/Domain.pm +408 -0
  30. git/usr/share/perl5/core_perl/Net/FTP.pm +2037 -0
  31. git/usr/share/perl5/core_perl/Net/NNTP.pm +1321 -0
  32. git/usr/share/perl5/core_perl/Net/Netrc.pm +366 -0
  33. git/usr/share/perl5/core_perl/Net/POP3.pm +882 -0
  34. git/usr/share/perl5/core_perl/Net/Ping.pm +2589 -0
  35. git/usr/share/perl5/core_perl/Net/SMTP.pm +1065 -0
  36. git/usr/share/perl5/core_perl/Net/Time.pm +203 -0
  37. git/usr/share/perl5/core_perl/Net/hostent.pm +148 -0
  38. git/usr/share/perl5/core_perl/Net/netent.pm +164 -0
  39. git/usr/share/perl5/core_perl/Net/protoent.pm +87 -0
  40. git/usr/share/perl5/core_perl/Net/servent.pm +104 -0
  41. git/usr/share/perl5/core_perl/Params/Check.pm +695 -0
  42. git/usr/share/perl5/core_perl/Perl/OSType.pm +225 -0
  43. git/usr/share/perl5/core_perl/PerlIO/scalar.pm +41 -0
  44. git/usr/share/perl5/core_perl/Search/Dict.pm +127 -0
  45. git/usr/share/perl5/core_perl/Term/ANSIColor.pm +1414 -0
  46. git/usr/share/perl5/core_perl/Term/Cap.pm +772 -0
  47. git/usr/share/perl5/core_perl/Term/Complete.pm +188 -0
  48. git/usr/share/perl5/core_perl/Term/ReadLine.pm +487 -0
  49. git/usr/share/perl5/core_perl/overload/numbers.pm +176 -0
  50. git/usr/share/perl5/core_perl/source/encoding.pm +71 -0
bin/api_call.py ADDED
@@ -0,0 +1,219 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ World-Level API Resilience Toolkit
3
+ ====================================
4
+ Handles: IP blocks, timeouts, rate limits, SSL errors, connection drops
5
+
6
+ Usage:
7
+ python api_call.py GET https://api.example.com/endpoint
8
+ python api_call.py POST https://api.example.com/data '{"key":"value"}'
9
+ python api_call.py GET https://api.example.com --proxy http://127.0.0.1:8080
10
+
11
+ Features:
12
+ - Auto Retry with Exponential Backoff
13
+ - Random User-Agent Rotation
14
+ - Connection Timeout Handling
15
+ - Rate Limit Detection (429) with Auto-Wait
16
+ - SSL Error Bypass Option
17
+ - Proxy Support (for mitmproxy or any proxy)
18
+ - Detailed Error Diagnosis
19
+ """
20
+
21
+ import sys
22
+ import time
23
+ import random
24
+ import json
25
+ import urllib.request
26
+ import urllib.error
27
+ import urllib.parse
28
+ import ssl
29
+ import os
30
+
31
+ # ─────────────────────────────────────────────
32
+ # CONFIGURATION - Edit these as needed
33
+ # ─────────────────────────────────────────────
34
+ MAX_RETRIES = 5
35
+ INITIAL_WAIT = 2 # seconds before first retry
36
+ TIMEOUT = 30 # request timeout in seconds
37
+ BYPASS_SSL = False # Set True if getting SSL errors (self-signed certs)
38
+ PROXY = None # e.g. "http://127.0.0.1:8080" for mitmproxy
39
+ # ─────────────────────────────────────────────
40
+
41
+ USER_AGENTS = [
42
+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/124.0 Safari/537.36",
43
+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:125.0) Gecko/20100101 Firefox/125.0",
44
+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 Safari/605.1.15",
45
+ "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 Chrome/122.0 Safari/537.36",
46
+ "python-httpx/0.27.0",
47
+ "axios/1.7.2",
48
+ "curl/8.7.1",
49
+ ]
50
+
51
+ DIAGNOSABLE_ERRORS = {
52
+ 400: "BAD REQUEST - Check your payload/params format",
53
+ 401: "UNAUTHORIZED - Check your API key/token",
54
+ 403: "FORBIDDEN - IP may be blocked or permissions missing",
55
+ 404: "NOT FOUND - Check the URL/endpoint",
56
+ 408: "REQUEST TIMEOUT - Server too slow, try increasing TIMEOUT",
57
+ 429: "RATE LIMITED - Waiting before retry...",
58
+ 500: "SERVER ERROR - Their problem, will retry",
59
+ 502: "BAD GATEWAY - Proxy/CDN issue, retrying",
60
+ 503: "SERVICE UNAVAILABLE - Server overloaded, retrying",
61
+ 504: "GATEWAY TIMEOUT - Network issue, retrying",
62
+ }
63
+
64
+
65
+ def make_request(method, url, data=None, headers=None, proxy=None, bypass_ssl=False, timeout=30):
66
+ """Core request function with all resilience features."""
67
+ if headers is None:
68
+ headers = {}
69
+
70
+ headers["User-Agent"] = random.choice(USER_AGENTS)
71
+ headers["Accept"] = "application/json, text/plain, */*"
72
+ headers["Accept-Language"] = "en-US,en;q=0.9"
73
+ headers["Connection"] = "keep-alive"
74
+
75
+ # SSL context
76
+ ctx = ssl.create_default_context()
77
+ if bypass_ssl:
78
+ ctx.check_hostname = False
79
+ ctx.verify_mode = ssl.CERT_NONE
80
+
81
+ # Proxy handler
82
+ handlers = []
83
+ if proxy:
84
+ proxy_handler = urllib.request.ProxyHandler({"http": proxy, "https": proxy})
85
+ handlers.append(proxy_handler)
86
+
87
+ https_handler = urllib.request.HTTPSHandler(context=ctx)
88
+ handlers.append(https_handler)
89
+ opener = urllib.request.build_opener(*handlers)
90
+
91
+ # Build request
92
+ body = None
93
+ if data:
94
+ if isinstance(data, dict):
95
+ body = json.dumps(data).encode("utf-8")
96
+ headers["Content-Type"] = "application/json"
97
+ else:
98
+ body = data.encode("utf-8") if isinstance(data, str) else data
99
+
100
+ req = urllib.request.Request(url, data=body, headers=headers, method=method.upper())
101
+
102
+ response = opener.open(req, timeout=timeout)
103
+ raw = response.read()
104
+ status = response.status
105
+
106
+ try:
107
+ result = json.loads(raw)
108
+ except Exception:
109
+ result = raw.decode("utf-8", errors="replace")
110
+
111
+ return status, result
112
+
113
+
114
+ def api_call(method, url, data=None, headers=None):
115
+ """Resilient API call with retry, backoff, and diagnosis."""
116
+ wait = INITIAL_WAIT
117
+ last_error = None
118
+
119
+ for attempt in range(1, MAX_RETRIES + 1):
120
+ try:
121
+ print(f"\n[Attempt {attempt}/{MAX_RETRIES}] {method.upper()} {url}")
122
+ status, result = make_request(
123
+ method, url, data=data, headers=headers,
124
+ proxy=PROXY, bypass_ssl=BYPASS_SSL, timeout=TIMEOUT
125
+ )
126
+
127
+ if status == 429:
128
+ retry_after = wait * 3
129
+ print(f" âš  {DIAGNOSABLE_ERRORS[429]}")
130
+ print(f" Waiting {retry_after}s before next attempt...")
131
+ time.sleep(retry_after)
132
+ wait = min(wait * 2, 120)
133
+ continue
134
+
135
+ if 200 <= status < 300:
136
+ print(f" ✓ SUCCESS ({status})")
137
+ return status, result
138
+
139
+ msg = DIAGNOSABLE_ERRORS.get(status, f"HTTP {status} - Unexpected error")
140
+ print(f" ✗ {msg}")
141
+
142
+ if status in (400, 401, 403, 404):
143
+ print(" → Non-retryable error. Stopping.")
144
+ return status, result
145
+
146
+ except urllib.error.URLError as e:
147
+ reason = str(e.reason)
148
+ print(f" ✗ CONNECTION ERROR: {reason}")
149
+
150
+ if "SSL" in reason or "certificate" in reason.lower():
151
+ print(" DIAGNOSIS: SSL/Certificate issue.")
152
+ print(" FIX: Set BYPASS_SSL = True in this script")
153
+ elif "timed out" in reason.lower():
154
+ print(" DIAGNOSIS: Connection timed out.")
155
+ print(" FIX: Increase TIMEOUT or check network")
156
+ elif "Name or service not known" in reason or "getaddrinfo" in reason:
157
+ print(" DIAGNOSIS: DNS resolution failed.")
158
+ print(" FIX: Check internet / try a different DNS (1.1.1.1)")
159
+ else:
160
+ print(" DIAGNOSIS: Network/connectivity issue.")
161
+ print(" FIX: Try mitmproxy or a proxy for routing")
162
+
163
+ last_error = e
164
+
165
+ except TimeoutError:
166
+ print(f" ✗ TIMEOUT after {TIMEOUT}s")
167
+ last_error = "Timeout"
168
+
169
+ except Exception as e:
170
+ print(f" ✗ UNEXPECTED: {e}")
171
+ last_error = e
172
+
173
+ if attempt < MAX_RETRIES:
174
+ print(f" ↻ Retrying in {wait}s... (backoff)")
175
+ time.sleep(wait)
176
+ wait = min(wait * 2, 60)
177
+
178
+ print(f"\n✗ All {MAX_RETRIES} attempts failed. Last error: {last_error}")
179
+ return None, None
180
+
181
+
182
+ def main():
183
+ if len(sys.argv) < 3:
184
+ print("Usage: python api_call.py <METHOD> <URL> [JSON_BODY] [--proxy PROXY_URL]")
185
+ print("Examples:")
186
+ print(" python api_call.py GET https://httpbin.org/get")
187
+ print(" python api_call.py POST https://httpbin.org/post '{\"key\":\"value\"}'")
188
+ print(" python api_call.py GET https://api.github.com/repos/cli/cli --proxy http://127.0.0.1:8080")
189
+ sys.exit(1)
190
+
191
+ method = sys.argv[1]
192
+ url = sys.argv[2]
193
+ data = None
194
+ global PROXY
195
+
196
+ args = sys.argv[3:]
197
+ for i, arg in enumerate(args):
198
+ if arg == "--proxy" and i + 1 < len(args):
199
+ PROXY = args[i + 1]
200
+ elif arg.startswith("{") or arg.startswith("["):
201
+ try:
202
+ data = json.loads(arg)
203
+ except Exception:
204
+ data = arg
205
+
206
+ status, result = api_call(method, url, data=data)
207
+
208
+ if result is not None:
209
+ print("\n─── RESPONSE ─────────────────────────────")
210
+ if isinstance(result, (dict, list)):
211
+ print(json.dumps(result, indent=2, ensure_ascii=False))
212
+ else:
213
+ print(result)
214
+ print("─────────────────────────────────────────")
215
+
216
+
217
+ if __name__ == "__main__":
218
+ main()
219
+
bin/big_file_sender.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Big File Streamer (Anti-Block Uploader)
3
+ =======================================
4
+ This script uploads MASSIVE files (10GB+) to APIs without crashing your RAM
5
+ or getting blocked by Windows Network limits. It streams the file directly
6
+ from the Hard Drive to the Network.
7
+
8
+ Usage:
9
+ python bin\big_file_sender.py https://api.example.com/upload my_huge_model.bin
10
+ python bin\big_file_sender.py https://api.example.com/upload data.zip --token "YOUR_API_KEY"
11
+ """
12
+
13
+ import sys
14
+ import argparse
15
+ import requests
16
+ import os
17
+ from tqdm import tqdm
18
+
19
+ def upload_huge_file(url, file_path, token=None):
20
+ if not os.path.exists(file_path):
21
+ print(f"[ERROR] File not found: {file_path}")
22
+ return
23
+
24
+ file_size = os.path.getsize(file_path)
25
+ file_name = os.path.basename(file_path)
26
+
27
+ print(f"[INFO] Preparing to stream: {file_name} ({file_size / (1024*1024):.2f} MB)")
28
+ print(f"[INFO] Target API: {url}")
29
+
30
+ headers = {
31
+ "Content-Type": "application/octet-stream",
32
+ "Content-Disposition": f'attachment; filename="{file_name}"',
33
+ # Keep connection alive so Windows doesn't drop it
34
+ "Connection": "keep-alive"
35
+ }
36
+
37
+ if token:
38
+ headers["Authorization"] = f"Bearer {token}"
39
+
40
+ # Create a streaming generator to read the file in chunks of 8MB
41
+ # This prevents Windows RAM overload and bypasses strict buffer limits
42
+ def file_stream_generator(filepath, chunk_size=8192*1024):
43
+ with open(filepath, 'rb') as f:
44
+ with tqdm(total=file_size, unit='B', unit_scale=True, desc="Uploading") as pbar:
45
+ while True:
46
+ chunk = f.read(chunk_size)
47
+ if not chunk:
48
+ break
49
+ yield chunk
50
+ pbar.update(len(chunk))
51
+
52
+ try:
53
+ # requests will stream the generator directly to the network socket
54
+ response = requests.post(
55
+ url,
56
+ data=file_stream_generator(file_path),
57
+ headers=headers,
58
+ stream=True,
59
+ timeout=3600 # 1 hour timeout for huge files
60
+ )
61
+
62
+ print("\n[SUCCESS] Upload Complete!")
63
+ print(f"Server Response ({response.status_code}): {response.text}")
64
+
65
+ except requests.exceptions.ConnectionError:
66
+ print("\n[ERROR] Connection Dropped by Target Server or Windows Firewall.")
67
+ print("Tip: If it keeps dropping, use the 'rclone' tool provided in your bin folder.")
68
+ except Exception as e:
69
+ print(f"\n[ERROR] Upload Failed: {e}")
70
+
71
+ if __name__ == "__main__":
72
+ parser = argparse.ArgumentParser(description="Upload huge files via streaming.")
73
+ parser.add_argument("url", help="The API Endpoint URL")
74
+ parser.add_argument("file", help="Path to the large file")
75
+ parser.add_argument("--token", help="Optional Bearer API Token", default=None)
76
+
77
+ args = parser.parse_args()
78
+ upload_huge_file(args.url, args.file, args.token)
bin/msbuild.bat ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ @echo off
2
+ dotnet msbuild %*
bin/rag_system.py ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Portable RAG (Retrieval-Augmented Generation) System
3
+ =====================================================
4
+ A completely portable, offline-capable RAG setup using ChromaDB and FastEmbed.
5
+
6
+ Usage:
7
+ 1. Add a Document:
8
+ python rag_system.py ingest my_document.pdf
9
+ python rag_system.py ingest my_notes.txt
10
+
11
+ 2. Query the Knowledge Base:
12
+ python rag_system.py query "What is the main topic?"
13
+ """
14
+
15
+ import sys
16
+ import os
17
+ import argparse
18
+ from pathlib import Path
19
+
20
+ # Fix for ChromaDB SQLite requirement in some environments
21
+ import sqlite3
22
+ import chromadb
23
+
24
+ # LangChain components
25
+ from langchain_community.document_loaders import PyPDFLoader, TextLoader
26
+ from langchain_text_splitters import RecursiveCharacterTextSplitter
27
+ from langchain_community.vectorstores import Chroma
28
+
29
+ # HuggingFace for Embeddings ^& LLM Generation
30
+ from langchain_huggingface import HuggingFaceEndpoint, HuggingFaceEmbeddings
31
+ from langchain_core.prompts import ChatPromptTemplate
32
+ from langchain_core.runnables import RunnablePassthrough
33
+ from langchain_core.output_parsers import StrOutputParser
34
+
35
+ # Configuration
36
+ DEVTOOLS_ROOT = Path(os.environ.get("DEVTOOLS_ROOT", os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
37
+ RAG_DATA_DIR = DEVTOOLS_ROOT / "rag_data"
38
+ RAG_DATA_DIR.mkdir(exist_ok=True)
39
+
40
+
41
+ # 1. Initialize Embeddings (LOCAL - No Token Needed)
42
+ print("[INFO] Loading Embedding Model (Local - This may take a moment on first run)...")
43
+ embeddings = HuggingFaceEmbeddings(
44
+ model_name="sentence-transformers/all-MiniLM-L6-v2",
45
+ model_kwargs={'device': 'cpu'}
46
+ )
47
+
48
+ # 2. Initialize Chroma Vector Database
49
+ print(f"[INFO] Connecting to ChromaDB at {RAG_DATA_DIR}...")
50
+ vectorstore = Chroma(
51
+ embedding_function=embeddings,
52
+ persist_directory=str(RAG_DATA_DIR)
53
+ )
54
+
55
+
56
+ def ingest_document(file_path: str):
57
+ """Reads a file, splits it into chunks, and saves to Vector DB."""
58
+ path = Path(file_path)
59
+ if not path.exists():
60
+ print(f"[ERROR] File not found: {file_path}")
61
+ sys.exit(1)
62
+
63
+ print(f"\n[1/3] Loading document: {path.name}...")
64
+ if path.suffix.lower() == '.pdf':
65
+ loader = PyPDFLoader(str(path))
66
+ elif path.suffix.lower() == '.txt':
67
+ loader = TextLoader(str(path), encoding='utf-8')
68
+ else:
69
+ print("[ERROR] Unsupported file type. Please use .pdf or .txt")
70
+ sys.exit(1)
71
+
72
+ docs = loader.load()
73
+ print(f" Loaded {len(docs)} pages/sections.")
74
+
75
+ print("[2/3] Splitting into chunks...")
76
+ text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)
77
+ splits = text_splitter.split_documents(docs)
78
+ print(f" Created {len(splits)} chunks.")
79
+
80
+ print("[3/3] Generating vectors and saving to database...")
81
+ vectorstore.add_documents(splits)
82
+ print("\n[SUCCESS] Document ingested successfully!")
83
+
84
+
85
+ def format_docs(docs):
86
+ return "\n\n".join(doc.page_content for doc in docs)
87
+
88
+
89
+ def query_rag(query: str):
90
+ """Retrieves relevant chunks and optionally uses an LLM to generate an answer."""
91
+ print(f"\n[Q] {query}\n")
92
+
93
+ # Step 1: Retrieval
94
+ print("─── RETRIEVED CONTEXT ────────────────────")
95
+ retriever = vectorstore.as_retriever(search_kwargs={"k": 3})
96
+ results = retriever.invoke(query)
97
+
98
+ if not results:
99
+ print("No relevant context found in the database.")
100
+ return
101
+
102
+ for i, doc in enumerate(results):
103
+ source = doc.metadata.get('source', 'Unknown')
104
+ page = doc.metadata.get('page', '')
105
+ page_info = f" (Page {page})" if page else ""
106
+ print(f"[{i+1}] Source: {os.path.basename(source)}{page_info}")
107
+ print(f" {doc.page_content[:300]}...\n")
108
+
109
+ # Step 2: Generation (Optional - Requires Token)
110
+ hf_token = os.environ.get("HF_TOKEN")
111
+ if hf_token:
112
+ print("\n─── AI GENERATED ANSWER ──────────────────")
113
+ try:
114
+ llm = HuggingFaceEndpoint(
115
+ repo_id="meta-llama/Meta-Llama-3-8B-Instruct",
116
+ task="text-generation",
117
+ max_new_tokens=512,
118
+ huggingfacehub_api_token=hf_token
119
+ )
120
+
121
+ template = """You are an assistant for question-answering tasks.
122
+ Use the following pieces of retrieved context to answer the question.
123
+ If you don't know the answer, say that you don't know.
124
+ Keep the answer concise and accurate based ONLY on the context.
125
+
126
+ Context: {context}
127
+
128
+ Question: {question}
129
+
130
+ Answer:"""
131
+ prompt = ChatPromptTemplate.from_template(template)
132
+
133
+ rag_chain = (
134
+ {"context": retriever | format_docs, "question": RunnablePassthrough()}
135
+ | prompt
136
+ | llm
137
+ | StrOutputParser()
138
+ )
139
+
140
+ response = rag_chain.invoke(query)
141
+ print(response.strip())
142
+
143
+ except Exception as e:
144
+ print(f"[WARN] Could not generate AI answer. (Are you logged into Hugging Face?)")
145
+ print(f" Error: {e}")
146
+ else:
147
+ print("\n[NOTE] HuggingFace token not found. Only returning retrieved documents.")
148
+ print(" Run 'hf auth login' in your terminal to enable AI Generation.")
149
+
150
+
151
+ def main():
152
+ parser = argparse.ArgumentParser(description="Portable RAG System")
153
+ subparsers = parser.add_subparsers(dest="command", help="Commands")
154
+
155
+ # Ingest command
156
+ ingest_parser = subparsers.add_parser("ingest", help="Ingest a document into the database")
157
+ ingest_parser.add_argument("file", type=str, help="Path to PDF or TXT file")
158
+
159
+ # Query command
160
+ query_parser = subparsers.add_parser("query", help="Query the database")
161
+ query_parser.add_argument("query", type=str, help="Your question")
162
+
163
+ args = parser.parse_args()
164
+
165
+ if args.command == "ingest":
166
+ ingest_document(args.file)
167
+ elif args.command == "query":
168
+ query_rag(args.query)
169
+ else:
170
+ parser.print_help()
171
+
172
+
173
+ if __name__ == "__main__":
174
+ main()
cuda_toolkit/version.json ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cuda" : {
3
+ "name" : "CUDA SDK",
4
+ "version" : "12.4.1"
5
+ },
6
+ "cuda_cccl" : {
7
+ "name" : "CUDA C++ Core Compute Libraries",
8
+ "version" : "12.4.127"
9
+ },
10
+ "cuda_cudart" : {
11
+ "name" : "CUDA Runtime (cudart)",
12
+ "version" : "12.4.127"
13
+ },
14
+ "cuda_cuobjdump" : {
15
+ "name" : "cuobjdump",
16
+ "version" : "12.4.127"
17
+ },
18
+ "cuda_cupti" : {
19
+ "name" : "CUPTI",
20
+ "version" : "12.4.127"
21
+ },
22
+ "cuda_cuxxfilt" : {
23
+ "name" : "CUDA cu++ filt",
24
+ "version" : "12.4.127"
25
+ },
26
+ "cuda_demo_suite" : {
27
+ "name" : "CUDA Demo Suite",
28
+ "version" : "12.4.127"
29
+ },
30
+ "cuda_nvcc" : {
31
+ "name" : "CUDA NVCC",
32
+ "version" : "12.4.131"
33
+ },
34
+ "cuda_nvdisasm" : {
35
+ "name" : "CUDA nvdisasm",
36
+ "version" : "12.4.127"
37
+ },
38
+ "cuda_nvml_dev" : {
39
+ "name" : "CUDA NVML Headers",
40
+ "version" : "12.4.127"
41
+ },
42
+ "cuda_nvprof" : {
43
+ "name" : "CUDA nvprof",
44
+ "version" : "12.4.127"
45
+ },
46
+ "cuda_nvprune" : {
47
+ "name" : "CUDA nvprune",
48
+ "version" : "12.4.127"
49
+ },
50
+ "cuda_nvrtc" : {
51
+ "name" : "CUDA NVRTC",
52
+ "version" : "12.4.127"
53
+ },
54
+ "cuda_nvtx" : {
55
+ "name" : "CUDA NVTX",
56
+ "version" : "12.4.127"
57
+ },
58
+ "cuda_nvvp" : {
59
+ "name" : "CUDA NVVP",
60
+ "version" : "12.4.127"
61
+ },
62
+ "cuda_opencl" : {
63
+ "name" : "CUDA OpenCL",
64
+ "version" : "12.4.127"
65
+ },
66
+ "cuda_sanitizer_api" : {
67
+ "name" : "CUDA Compute Sanitizer API",
68
+ "version" : "12.4.127"
69
+ },
70
+ "libcublas" : {
71
+ "name" : "CUDA cuBLAS",
72
+ "version" : "12.4.5.8"
73
+ },
74
+ "libcufft" : {
75
+ "name" : "CUDA cuFFT",
76
+ "version" : "11.2.1.3"
77
+ },
78
+ "libcurand" : {
79
+ "name" : "CUDA cuRAND",
80
+ "version" : "10.3.5.147"
81
+ },
82
+ "libcusolver" : {
83
+ "name" : "CUDA cuSOLVER",
84
+ "version" : "11.6.1.9"
85
+ },
86
+ "libcusparse" : {
87
+ "name" : "CUDA cuSPARSE",
88
+ "version" : "12.3.1.170"
89
+ },
90
+ "libnpp" : {
91
+ "name" : "CUDA NPP",
92
+ "version" : "12.2.5.30"
93
+ },
94
+ "libnvfatbin" : {
95
+ "name" : "Fatbin interaction library",
96
+ "version" : "12.4.127"
97
+ },
98
+ "libnvjitlink" : {
99
+ "name" : "JIT Linker Library",
100
+ "version" : "12.4.127"
101
+ },
102
+ "libnvjpeg" : {
103
+ "name" : "CUDA nvJPEG",
104
+ "version" : "12.3.1.117"
105
+ },
106
+ "nsight_compute" : {
107
+ "name" : "Nsight Compute",
108
+ "version" : "2024.1.1.4"
109
+ },
110
+ "nsight_vse" : {
111
+ "name" : "Nsight Visual Studio Edition (VSE)",
112
+ "version" : "2024.1.1.24072"
113
+ },
114
+ "nvidia_driver" : {
115
+ "name" : "NVIDIA Windows Driver",
116
+ "version" : "551.78"
117
+ }
118
+ }
git/usr/share/perl5/core_perl/I18N/LangTags.pm ADDED
@@ -0,0 +1,887 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ # Time-stamp: "2004-10-06 23:26:33 ADT"
3
+ # Sean M. Burke <sburke@cpan.org>
4
+
5
+ require 5.000;
6
+ package I18N::LangTags;
7
+ use strict;
8
+ require Exporter;
9
+ our @ISA = qw(Exporter);
10
+ our @EXPORT = qw();
11
+ our @EXPORT_OK = qw(is_language_tag same_language_tag
12
+ extract_language_tags super_languages
13
+ similarity_language_tag is_dialect_of
14
+ locale2language_tag alternate_language_tags
15
+ encode_language_tag panic_languages
16
+ implicate_supers
17
+ implicate_supers_strictly
18
+ );
19
+ our %EXPORT_TAGS = ('ALL' => \@EXPORT_OK);
20
+
21
+ our $VERSION = "0.45";
22
+ our %Panic;
23
+
24
+ sub uniq { my %seen; return grep(!($seen{$_}++), @_); } # a util function
25
+
26
+
27
+ =head1 NAME
28
+
29
+ I18N::LangTags - functions for dealing with RFC3066-style language tags
30
+
31
+ =head1 SYNOPSIS
32
+
33
+ use I18N::LangTags();
34
+
35
+ ...or specify whichever of those functions you want to import, like so:
36
+
37
+ use I18N::LangTags qw(implicate_supers similarity_language_tag);
38
+
39
+ All the exportable functions are listed below -- you're free to import
40
+ only some, or none at all. By default, none are imported. If you
41
+ say:
42
+
43
+ use I18N::LangTags qw(:ALL)
44
+
45
+ ...then all are exported. (This saves you from having to use
46
+ something less obvious like C<use I18N::LangTags qw(/./)>.)
47
+
48
+ If you don't import any of these functions, assume a C<&I18N::LangTags::>
49
+ in front of all the function names in the following examples.
50
+
51
+ =head1 DESCRIPTION
52
+
53
+ Language tags are a formalism, described in RFC 3066 (obsoleting
54
+ 1766), for declaring what language form (language and possibly
55
+ dialect) a given chunk of information is in.
56
+
57
+ This library provides functions for common tasks involving language
58
+ tags as they are needed in a variety of protocols and applications.
59
+
60
+ Please see the "See Also" references for a thorough explanation
61
+ of how to correctly use language tags.
62
+
63
+ =over
64
+
65
+ =cut
66
+
67
+ ###########################################################################
68
+
69
+ =item * the function is_language_tag($lang1)
70
+
71
+ Returns true iff $lang1 is a formally valid language tag.
72
+
73
+ is_language_tag("fr") is TRUE
74
+ is_language_tag("x-jicarilla") is FALSE
75
+ (Subtags can be 8 chars long at most -- 'jicarilla' is 9)
76
+
77
+ is_language_tag("sgn-US") is TRUE
78
+ (That's American Sign Language)
79
+
80
+ is_language_tag("i-Klikitat") is TRUE
81
+ (True without regard to the fact noone has actually
82
+ registered Klikitat -- it's a formally valid tag)
83
+
84
+ is_language_tag("fr-patois") is TRUE
85
+ (Formally valid -- altho descriptively weak!)
86
+
87
+ is_language_tag("Spanish") is FALSE
88
+ is_language_tag("french-patois") is FALSE
89
+ (No good -- first subtag has to match
90
+ /^([xXiI]|[a-zA-Z]{2,3})$/ -- see RFC3066)
91
+
92
+ is_language_tag("x-borg-prot2532") is TRUE
93
+ (Yes, subtags can contain digits, as of RFC3066)
94
+
95
+ =cut
96
+
97
+ sub is_language_tag {
98
+
99
+ ## Changes in the language tagging standards may have to be reflected here.
100
+
101
+ my($tag) = lc($_[0]);
102
+
103
+ return 0 if $tag eq "i" or $tag eq "x";
104
+ # Bad degenerate cases that the following
105
+ # regexp would erroneously let pass
106
+
107
+ return $tag =~
108
+ /^(?: # First subtag
109
+ [xi] | [a-z]{2,3}
110
+ )
111
+ (?: # Subtags thereafter
112
+ - # separator
113
+ [a-z0-9]{1,8} # subtag
114
+ )*
115
+ $/xs ? 1 : 0;
116
+ }
117
+
118
+ ###########################################################################
119
+
120
+ =item * the function extract_language_tags($whatever)
121
+
122
+ Returns a list of whatever looks like formally valid language tags
123
+ in $whatever. Not very smart, so don't get too creative with
124
+ what you want to feed it.
125
+
126
+ extract_language_tags("fr, fr-ca, i-mingo")
127
+ returns: ('fr', 'fr-ca', 'i-mingo')
128
+
129
+ extract_language_tags("It's like this: I'm in fr -- French!")
130
+ returns: ('It', 'in', 'fr')
131
+ (So don't just feed it any old thing.)
132
+
133
+ The output is untainted. If you don't know what tainting is,
134
+ don't worry about it.
135
+
136
+ =cut
137
+
138
+ sub extract_language_tags {
139
+
140
+ ## Changes in the language tagging standards may have to be reflected here.
141
+
142
+ my($text) =
143
+ $_[0] =~ m/(.+)/ # to make for an untainted result
144
+ ? $1 : ''
145
+ ;
146
+
147
+ return grep(!m/^[ixIX]$/s, # 'i' and 'x' aren't good tags
148
+ $text =~
149
+ m/
150
+ \b
151
+ (?: # First subtag
152
+ [iIxX] | [a-zA-Z]{2,3}
153
+ )
154
+ (?: # Subtags thereafter
155
+ - # separator
156
+ [a-zA-Z0-9]{1,8} # subtag
157
+ )*
158
+ \b
159
+ /xsg
160
+ );
161
+ }
162
+
163
+ ###########################################################################
164
+
165
+ =item * the function same_language_tag($lang1, $lang2)
166
+
167
+ Returns true iff $lang1 and $lang2 are acceptable variant tags
168
+ representing the same language-form.
169
+
170
+ same_language_tag('x-kadara', 'i-kadara') is TRUE
171
+ (The x/i- alternation doesn't matter)
172
+ same_language_tag('X-KADARA', 'i-kadara') is TRUE
173
+ (...and neither does case)
174
+ same_language_tag('en', 'en-US') is FALSE
175
+ (all-English is not the SAME as US English)
176
+ same_language_tag('x-kadara', 'x-kadar') is FALSE
177
+ (these are totally unrelated tags)
178
+ same_language_tag('no-bok', 'nb') is TRUE
179
+ (no-bok is a legacy tag for nb (Norwegian Bokmal))
180
+
181
+ C<same_language_tag> works by just seeing whether
182
+ C<encode_language_tag($lang1)> is the same as
183
+ C<encode_language_tag($lang2)>.
184
+
185
+ (Yes, I know this function is named a bit oddly. Call it historic
186
+ reasons.)
187
+
188
+ =cut
189
+
190
+ sub same_language_tag {
191
+ my $el1 = &encode_language_tag($_[0]);
192
+ return 0 unless defined $el1;
193
+ # this avoids the problem of
194
+ # encode_language_tag($lang1) eq and encode_language_tag($lang2)
195
+ # being true if $lang1 and $lang2 are both undef
196
+
197
+ return $el1 eq &encode_language_tag($_[1]) ? 1 : 0;
198
+ }
199
+
200
+ ###########################################################################
201
+
202
+ =item * the function similarity_language_tag($lang1, $lang2)
203
+
204
+ Returns an integer representing the degree of similarity between
205
+ tags $lang1 and $lang2 (the order of which does not matter), where
206
+ similarity is the number of common elements on the left,
207
+ without regard to case and to x/i- alternation.
208
+
209
+ similarity_language_tag('fr', 'fr-ca') is 1
210
+ (one element in common)
211
+ similarity_language_tag('fr-ca', 'fr-FR') is 1
212
+ (one element in common)
213
+
214
+ similarity_language_tag('fr-CA-joual',
215
+ 'fr-CA-PEI') is 2
216
+ similarity_language_tag('fr-CA-joual', 'fr-CA') is 2
217
+ (two elements in common)
218
+
219
+ similarity_language_tag('x-kadara', 'i-kadara') is 1
220
+ (x/i- doesn't matter)
221
+
222
+ similarity_language_tag('en', 'x-kadar') is 0
223
+ similarity_language_tag('x-kadara', 'x-kadar') is 0
224
+ (unrelated tags -- no similarity)
225
+
226
+ similarity_language_tag('i-cree-syllabic',
227
+ 'i-cherokee-syllabic') is 0
228
+ (no B<leftmost> elements in common!)
229
+
230
+ =cut
231
+
232
+ sub similarity_language_tag {
233
+ my $lang1 = &encode_language_tag($_[0]);
234
+ my $lang2 = &encode_language_tag($_[1]);
235
+ # And encode_language_tag takes care of the whole
236
+ # no-nyn==nn, i-hakka==zh-hakka, etc, things
237
+
238
+ # NB: (i-sil-...)? (i-sgn-...)?
239
+
240
+ return undef if !defined($lang1) and !defined($lang2);
241
+ return 0 if !defined($lang1) or !defined($lang2);
242
+
243
+ my @l1_subtags = split('-', $lang1);
244
+ my @l2_subtags = split('-', $lang2);
245
+ my $similarity = 0;
246
+
247
+ while(@l1_subtags and @l2_subtags) {
248
+ if(shift(@l1_subtags) eq shift(@l2_subtags)) {
249
+ ++$similarity;
250
+ } else {
251
+ last;
252
+ }
253
+ }
254
+ return $similarity;
255
+ }
256
+
257
+ ###########################################################################
258
+
259
+ =item * the function is_dialect_of($lang1, $lang2)
260
+
261
+ Returns true iff language tag $lang1 represents a subform of
262
+ language tag $lang2.
263
+
264
+ B<Get the order right! It doesn't work the other way around!>
265
+
266
+ is_dialect_of('en-US', 'en') is TRUE
267
+ (American English IS a dialect of all-English)
268
+
269
+ is_dialect_of('fr-CA-joual', 'fr-CA') is TRUE
270
+ is_dialect_of('fr-CA-joual', 'fr') is TRUE
271
+ (Joual is a dialect of (a dialect of) French)
272
+
273
+ is_dialect_of('en', 'en-US') is FALSE
274
+ (all-English is a NOT dialect of American English)
275
+
276
+ is_dialect_of('fr', 'en-CA') is FALSE
277
+
278
+ is_dialect_of('en', 'en' ) is TRUE
279
+ is_dialect_of('en-US', 'en-US') is TRUE
280
+ (B<Note:> these are degenerate cases)
281
+
282
+ is_dialect_of('i-mingo-tom', 'x-Mingo') is TRUE
283
+ (the x/i thing doesn't matter, nor does case)
284
+
285
+ is_dialect_of('nn', 'no') is TRUE
286
+ (because 'nn' (New Norse) is aliased to 'no-nyn',
287
+ as a special legacy case, and 'no-nyn' is a
288
+ subform of 'no' (Norwegian))
289
+
290
+ =cut
291
+
292
+ sub is_dialect_of {
293
+
294
+ my $lang1 = &encode_language_tag($_[0]);
295
+ my $lang2 = &encode_language_tag($_[1]);
296
+
297
+ return undef if !defined($lang1) and !defined($lang2);
298
+ return 0 if !defined($lang1) or !defined($lang2);
299
+
300
+ return 1 if $lang1 eq $lang2;
301
+ return 0 if length($lang1) < length($lang2);
302
+
303
+ $lang1 .= '-';
304
+ $lang2 .= '-';
305
+ return
306
+ (substr($lang1, 0, length($lang2)) eq $lang2) ? 1 : 0;
307
+ }
308
+
309
+ ###########################################################################
310
+
311
+ =item * the function super_languages($lang1)
312
+
313
+ Returns a list of language tags that are superordinate tags to $lang1
314
+ -- it gets this by removing subtags from the end of $lang1 until
315
+ nothing (or just "i" or "x") is left.
316
+
317
+ super_languages("fr-CA-joual") is ("fr-CA", "fr")
318
+
319
+ super_languages("en-AU") is ("en")
320
+
321
+ super_languages("en") is empty-list, ()
322
+
323
+ super_languages("i-cherokee") is empty-list, ()
324
+ ...not ("i"), which would be illegal as well as pointless.
325
+
326
+ If $lang1 is not a valid language tag, returns empty-list in
327
+ a list context, undef in a scalar context.
328
+
329
+ A notable and rather unavoidable problem with this method:
330
+ "x-mingo-tom" has an "x" because the whole tag isn't an
331
+ IANA-registered tag -- but super_languages('x-mingo-tom') is
332
+ ('x-mingo') -- which isn't really right, since 'i-mingo' is
333
+ registered. But this module has no way of knowing that. (But note
334
+ that same_language_tag('x-mingo', 'i-mingo') is TRUE.)
335
+
336
+ More importantly, you assume I<at your peril> that superordinates of
337
+ $lang1 are mutually intelligible with $lang1. Consider this
338
+ carefully.
339
+
340
+ =cut
341
+
342
+ sub super_languages {
343
+ my $lang1 = $_[0];
344
+ return() unless defined($lang1) && &is_language_tag($lang1);
345
+
346
+ # a hack for those annoying new (2001) tags:
347
+ $lang1 =~ s/^nb\b/no-bok/i; # yes, backwards
348
+ $lang1 =~ s/^nn\b/no-nyn/i; # yes, backwards
349
+ $lang1 =~ s/^[ix](-hakka\b)/zh$1/i; # goes the right way
350
+ # i-hakka-bork-bjork-bjark => zh-hakka-bork-bjork-bjark
351
+
352
+ my @l1_subtags = split('-', $lang1);
353
+
354
+ ## Changes in the language tagging standards may have to be reflected here.
355
+
356
+ # NB: (i-sil-...)?
357
+
358
+ my @supers = ();
359
+ foreach my $bit (@l1_subtags) {
360
+ push @supers,
361
+ scalar(@supers) ? ($supers[-1] . '-' . $bit) : $bit;
362
+ }
363
+ pop @supers if @supers;
364
+ shift @supers if @supers && $supers[0] =~ m<^[iIxX]$>s;
365
+ return reverse @supers;
366
+ }
367
+
368
+ ###########################################################################
369
+
370
+ =item * the function locale2language_tag($locale_identifier)
371
+
372
+ This takes a locale name (like "en", "en_US", or "en_US.ISO8859-1")
373
+ and maps it to a language tag. If it's not mappable (as with,
374
+ notably, "C" and "POSIX"), this returns empty-list in a list context,
375
+ or undef in a scalar context.
376
+
377
+ locale2language_tag("en") is "en"
378
+
379
+ locale2language_tag("en_US") is "en-US"
380
+
381
+ locale2language_tag("en_US.ISO8859-1") is "en-US"
382
+
383
+ locale2language_tag("C") is undef or ()
384
+
385
+ locale2language_tag("POSIX") is undef or ()
386
+
387
+ locale2language_tag("POSIX") is undef or ()
388
+
389
+ I'm not totally sure that locale names map satisfactorily to language
390
+ tags. Think REAL hard about how you use this. YOU HAVE BEEN WARNED.
391
+
392
+ The output is untainted. If you don't know what tainting is,
393
+ don't worry about it.
394
+
395
+ =cut
396
+
397
+ sub locale2language_tag {
398
+ my $lang =
399
+ $_[0] =~ m/(.+)/ # to make for an untainted result
400
+ ? $1 : ''
401
+ ;
402
+
403
+ return $lang if &is_language_tag($lang); # like "en"
404
+
405
+ $lang =~ tr<_><->; # "en_US" -> en-US
406
+ $lang =~ s<(?:[\.\@][-_a-zA-Z0-9]+)+$><>s; # "en_US.ISO8859-1" -> en-US
407
+ # it_IT.utf8@euro => it-IT
408
+
409
+ return $lang if &is_language_tag($lang);
410
+
411
+ return;
412
+ }
413
+
414
+ ###########################################################################
415
+
416
+ =item * the function encode_language_tag($lang1)
417
+
418
+ This function, if given a language tag, returns an encoding of it such
419
+ that:
420
+
421
+ * tags representing different languages never get the same encoding.
422
+
423
+ * tags representing the same language always get the same encoding.
424
+
425
+ * an encoding of a formally valid language tag always is a string
426
+ value that is defined, has length, and is true if considered as a
427
+ boolean.
428
+
429
+ Note that the encoding itself is B<not> a formally valid language tag.
430
+ Note also that you cannot, currently, go from an encoding back to a
431
+ language tag that it's an encoding of.
432
+
433
+ Note also that you B<must> consider the encoded value as atomic; i.e.,
434
+ you should not consider it as anything but an opaque, unanalysable
435
+ string value. (The internals of the encoding method may change in
436
+ future versions, as the language tagging standard changes over time.)
437
+
438
+ C<encode_language_tag> returns undef if given anything other than a
439
+ formally valid language tag.
440
+
441
+ The reason C<encode_language_tag> exists is because different language
442
+ tags may represent the same language; this is normally treatable with
443
+ C<same_language_tag>, but consider this situation:
444
+
445
+ You have a data file that expresses greetings in different languages.
446
+ Its format is "[language tag]=[how to say 'Hello']", like:
447
+
448
+ en-US=Hiho
449
+ fr=Bonjour
450
+ i-mingo=Hau'
451
+
452
+ And suppose you write a program that reads that file and then runs as
453
+ a daemon, answering client requests that specify a language tag and
454
+ then expect the string that says how to greet in that language. So an
455
+ interaction looks like:
456
+
457
+ greeting-client asks: fr
458
+ greeting-server answers: Bonjour
459
+
460
+ So far so good. But suppose the way you're implementing this is:
461
+
462
+ my %greetings;
463
+ die unless open(IN, "<", "in.dat");
464
+ while(<IN>) {
465
+ chomp;
466
+ next unless /^([^=]+)=(.+)/s;
467
+ my($lang, $expr) = ($1, $2);
468
+ $greetings{$lang} = $expr;
469
+ }
470
+ close(IN);
471
+
472
+ at which point %greetings has the contents:
473
+
474
+ "en-US" => "Hiho"
475
+ "fr" => "Bonjour"
476
+ "i-mingo" => "Hau'"
477
+
478
+ And suppose then that you answer client requests for language $wanted
479
+ by just looking up $greetings{$wanted}.
480
+
481
+ If the client asks for "fr", that will look up successfully in
482
+ %greetings, to the value "Bonjour". And if the client asks for
483
+ "i-mingo", that will look up successfully in %greetings, to the value
484
+ "Hau'".
485
+
486
+ But if the client asks for "i-Mingo" or "x-mingo", or "Fr", then the
487
+ lookup in %greetings fails. That's the Wrong Thing.
488
+
489
+ You could instead do lookups on $wanted with:
490
+
491
+ use I18N::LangTags qw(same_language_tag);
492
+ my $response = '';
493
+ foreach my $l2 (keys %greetings) {
494
+ if(same_language_tag($wanted, $l2)) {
495
+ $response = $greetings{$l2};
496
+ last;
497
+ }
498
+ }
499
+
500
+ But that's rather inefficient. A better way to do it is to start your
501
+ program with:
502
+
503
+ use I18N::LangTags qw(encode_language_tag);
504
+ my %greetings;
505
+ die unless open(IN, "<", "in.dat");
506
+ while(<IN>) {
507
+ chomp;
508
+ next unless /^([^=]+)=(.+)/s;
509
+ my($lang, $expr) = ($1, $2);
510
+ $greetings{
511
+ encode_language_tag($lang)
512
+ } = $expr;
513
+ }
514
+ close(IN);
515
+
516
+ and then just answer client requests for language $wanted by just
517
+ looking up
518
+
519
+ $greetings{encode_language_tag($wanted)}
520
+
521
+ And that does the Right Thing.
522
+
523
+ =cut
524
+
525
+ sub encode_language_tag {
526
+ # Only similarity_language_tag() is allowed to analyse encodings!
527
+
528
+ ## Changes in the language tagging standards may have to be reflected here.
529
+
530
+ my($tag) = $_[0] || return undef;
531
+ return undef unless &is_language_tag($tag);
532
+
533
+ # For the moment, these legacy variances are few enough that
534
+ # we can just handle them here with regexps.
535
+ $tag =~ s/^iw\b/he/i; # Hebrew
536
+ $tag =~ s/^in\b/id/i; # Indonesian
537
+ $tag =~ s/^cre\b/cr/i; # Cree
538
+ $tag =~ s/^jw\b/jv/i; # Javanese
539
+ $tag =~ s/^[ix]-lux\b/lb/i; # Luxemburger
540
+ $tag =~ s/^[ix]-navajo\b/nv/i; # Navajo
541
+ $tag =~ s/^ji\b/yi/i; # Yiddish
542
+ # SMB 2003 -- Hm. There's a bunch of new XXX->YY variances now,
543
+ # but maybe they're all so obscure I can ignore them. "Obscure"
544
+ # meaning either that the language is obscure, and/or that the
545
+ # XXX form was extant so briefly that it's unlikely it was ever
546
+ # used. I hope.
547
+ #
548
+ # These go FROM the simplex to complex form, to get
549
+ # similarity-comparison right. And that's okay, since
550
+ # similarity_language_tag is the only thing that
551
+ # analyzes our output.
552
+ $tag =~ s/^[ix]-hakka\b/zh-hakka/i; # Hakka
553
+ $tag =~ s/^nb\b/no-bok/i; # BACKWARDS for Bokmal
554
+ $tag =~ s/^nn\b/no-nyn/i; # BACKWARDS for Nynorsk
555
+
556
+ $tag =~ s/^[xiXI]-//s;
557
+ # Just lop off any leading "x/i-"
558
+
559
+ return "~" . uc($tag);
560
+ }
561
+
562
+ #--------------------------------------------------------------------------
563
+
564
+ =item * the function alternate_language_tags($lang1)
565
+
566
+ This function, if given a language tag, returns all language tags that
567
+ are alternate forms of this language tag. (I.e., tags which refer to
568
+ the same language.) This is meant to handle legacy tags caused by
569
+ the minor changes in language tag standards over the years; and
570
+ the x-/i- alternation is also dealt with.
571
+
572
+ Note that this function does I<not> try to equate new (and never-used,
573
+ and unusable)
574
+ ISO639-2 three-letter tags to old (and still in use) ISO639-1
575
+ two-letter equivalents -- like "ara" -> "ar" -- because
576
+ "ara" has I<never> been in use as an Internet language tag,
577
+ and RFC 3066 stipulates that it never should be, since a shorter
578
+ tag ("ar") exists.
579
+
580
+ Examples:
581
+
582
+ alternate_language_tags('no-bok') is ('nb')
583
+ alternate_language_tags('nb') is ('no-bok')
584
+ alternate_language_tags('he') is ('iw')
585
+ alternate_language_tags('iw') is ('he')
586
+ alternate_language_tags('i-hakka') is ('zh-hakka', 'x-hakka')
587
+ alternate_language_tags('zh-hakka') is ('i-hakka', 'x-hakka')
588
+ alternate_language_tags('en') is ()
589
+ alternate_language_tags('x-mingo-tom') is ('i-mingo-tom')
590
+ alternate_language_tags('x-klikitat') is ('i-klikitat')
591
+ alternate_language_tags('i-klikitat') is ('x-klikitat')
592
+
593
+ This function returns empty-list if given anything other than a formally
594
+ valid language tag.
595
+
596
+ =cut
597
+
598
+ my %alt = qw( i x x i I X X I );
599
+ sub alternate_language_tags {
600
+ my $tag = $_[0];
601
+ return() unless &is_language_tag($tag);
602
+
603
+ my @em; # push 'em real goood!
604
+
605
+ # For the moment, these legacy variances are few enough that
606
+ # we can just handle them here with regexps.
607
+
608
+ if( $tag =~ m/^[ix]-hakka\b(.*)/i) {push @em, "zh-hakka$1";
609
+ } elsif($tag =~ m/^zh-hakka\b(.*)/i) { push @em, "x-hakka$1", "i-hakka$1";
610
+
611
+ } elsif($tag =~ m/^he\b(.*)/i) { push @em, "iw$1";
612
+ } elsif($tag =~ m/^iw\b(.*)/i) { push @em, "he$1";
613
+
614
+ } elsif($tag =~ m/^in\b(.*)/i) { push @em, "id$1";
615
+ } elsif($tag =~ m/^id\b(.*)/i) { push @em, "in$1";
616
+
617
+ } elsif($tag =~ m/^[ix]-lux\b(.*)/i) { push @em, "lb$1";
618
+ } elsif($tag =~ m/^lb\b(.*)/i) { push @em, "i-lux$1", "x-lux$1";
619
+
620
+ } elsif($tag =~ m/^[ix]-navajo\b(.*)/i) { push @em, "nv$1";
621
+ } elsif($tag =~ m/^nv\b(.*)/i) { push @em, "i-navajo$1", "x-navajo$1";
622
+
623
+ } elsif($tag =~ m/^yi\b(.*)/i) { push @em, "ji$1";
624
+ } elsif($tag =~ m/^ji\b(.*)/i) { push @em, "yi$1";
625
+
626
+ } elsif($tag =~ m/^nb\b(.*)/i) { push @em, "no-bok$1";
627
+ } elsif($tag =~ m/^no-bok\b(.*)/i) { push @em, "nb$1";
628
+
629
+ } elsif($tag =~ m/^nn\b(.*)/i) { push @em, "no-nyn$1";
630
+ } elsif($tag =~ m/^no-nyn\b(.*)/i) { push @em, "nn$1";
631
+ }
632
+
633
+ push @em, $alt{$1} . $2 if $tag =~ /^([XIxi])(-.+)/;
634
+ return @em;
635
+ }
636
+
637
+ ###########################################################################
638
+
639
+ {
640
+ # Init %Panic...
641
+
642
+ my @panic = ( # MUST all be lowercase!
643
+ # Only large ("national") languages make it in this list.
644
+ # If you, as a user, are so bizarre that the /only/ language
645
+ # you claim to accept is Galician, then no, we won't do you
646
+ # the favor of providing Catalan as a panic-fallback for
647
+ # you. Because if I start trying to add "little languages" in
648
+ # here, I'll just go crazy.
649
+
650
+ # Scandinavian lgs. All based on opinion and hearsay.
651
+ 'sv' => [qw(nb no da nn)],
652
+ 'da' => [qw(nb no sv nn)], # I guess
653
+ [qw(no nn nb)], [qw(no nn nb sv da)],
654
+ 'is' => [qw(da sv no nb nn)],
655
+ 'fo' => [qw(da is no nb nn sv)], # I guess
656
+
657
+ # I think this is about the extent of tolerable intelligibility
658
+ # among large modern Romance languages.
659
+ 'pt' => [qw(es ca it fr)], # Portuguese, Spanish, Catalan, Italian, French
660
+ 'ca' => [qw(es pt it fr)],
661
+ 'es' => [qw(ca it fr pt)],
662
+ 'it' => [qw(es fr ca pt)],
663
+ 'fr' => [qw(es it ca pt)],
664
+
665
+ # Also assume that speakers of the main Indian languages prefer
666
+ # to read/hear Hindi over English
667
+ [qw(
668
+ as bn gu kn ks kok ml mni mr ne or pa sa sd te ta ur
669
+ )] => 'hi',
670
+ # Assamese, Bengali, Gujarati, [Hindi,] Kannada (Kanarese), Kashmiri,
671
+ # Konkani, Malayalam, Meithei (Manipuri), Marathi, Nepali, Oriya,
672
+ # Punjabi, Sanskrit, Sindhi, Telugu, Tamil, and Urdu.
673
+ 'hi' => [qw(bn pa as or)],
674
+ # I welcome finer data for the other Indian languages.
675
+ # E.g., what should Oriya's list be, besides just Hindi?
676
+
677
+ # And the panic languages for English is, of course, nil!
678
+
679
+ # My guesses at Slavic intelligibility:
680
+ ([qw(ru be uk)]) x 2, # Russian, Belarusian, Ukrainian
681
+ ([qw(sr hr bs)]) x 2, # Serbian, Croatian, Bosnian
682
+ 'cs' => 'sk', 'sk' => 'cs', # Czech + Slovak
683
+
684
+ 'ms' => 'id', 'id' => 'ms', # Malay + Indonesian
685
+
686
+ 'et' => 'fi', 'fi' => 'et', # Estonian + Finnish
687
+
688
+ #?? 'lo' => 'th', 'th' => 'lo', # Lao + Thai
689
+
690
+ );
691
+ my($k,$v);
692
+ while(@panic) {
693
+ ($k,$v) = splice(@panic,0,2);
694
+ foreach my $k (ref($k) ? @$k : $k) {
695
+ foreach my $v (ref($v) ? @$v : $v) {
696
+ push @{$Panic{$k} ||= []}, $v unless $k eq $v;
697
+ }
698
+ }
699
+ }
700
+ }
701
+
702
+ =item * the function @langs = panic_languages(@accept_languages)
703
+
704
+ This function takes a list of 0 or more language
705
+ tags that constitute a given user's Accept-Language list, and
706
+ returns a list of tags for I<other> (non-super)
707
+ languages that are probably acceptable to the user, to be
708
+ used I<if all else fails>.
709
+
710
+ For example, if a user accepts only 'ca' (Catalan) and
711
+ 'es' (Spanish), and the documents/interfaces you have
712
+ available are just in German, Italian, and Chinese, then
713
+ the user will most likely want the Italian one (and not
714
+ the Chinese or German one!), instead of getting
715
+ nothing. So C<panic_languages('ca', 'es')> returns
716
+ a list containing 'it' (Italian).
717
+
718
+ English ('en') is I<always> in the return list, but
719
+ whether it's at the very end or not depends
720
+ on the input languages. This function works by consulting
721
+ an internal table that stipulates what common
722
+ languages are "close" to each other.
723
+
724
+ A useful construct you might consider using is:
725
+
726
+ @fallbacks = super_languages(@accept_languages);
727
+ push @fallbacks, panic_languages(
728
+ @accept_languages, @fallbacks,
729
+ );
730
+
731
+ =cut
732
+
733
+ sub panic_languages {
734
+ # When in panic or in doubt, run in circles, scream, and shout!
735
+ my(@out, %seen);
736
+ foreach my $t (@_) {
737
+ next unless $t;
738
+ next if $seen{$t}++; # so we don't return it or hit it again
739
+ # push @out, super_languages($t); # nah, keep that separate
740
+ push @out, @{ $Panic{lc $t} || next };
741
+ }
742
+ return grep !$seen{$_}++, @out, 'en';
743
+ }
744
+
745
+ #---------------------------------------------------------------------------
746
+ #---------------------------------------------------------------------------
747
+
748
+ =item * the function implicate_supers( ...languages... )
749
+
750
+ This takes a list of strings (which are presumed to be language-tags;
751
+ strings that aren't, are ignored); and after each one, this function
752
+ inserts super-ordinate forms that don't already appear in the list.
753
+ The original list, plus these insertions, is returned.
754
+
755
+ In other words, it takes this:
756
+
757
+ pt-br de-DE en-US fr pt-br-janeiro
758
+
759
+ and returns this:
760
+
761
+ pt-br pt de-DE de en-US en fr pt-br-janeiro
762
+
763
+ This function is most useful in the idiom
764
+
765
+ implicate_supers( I18N::LangTags::Detect::detect() );
766
+
767
+ (See L<I18N::LangTags::Detect>.)
768
+
769
+
770
+ =item * the function implicate_supers_strictly( ...languages... )
771
+
772
+ This works like C<implicate_supers> except that the implicated
773
+ forms are added to the end of the return list.
774
+
775
+ In other words, implicate_supers_strictly takes a list of strings
776
+ (which are presumed to be language-tags; strings that aren't, are
777
+ ignored) and after the whole given list, it inserts the super-ordinate forms
778
+ of all given tags, minus any tags that already appear in the input list.
779
+
780
+ In other words, it takes this:
781
+
782
+ pt-br de-DE en-US fr pt-br-janeiro
783
+
784
+ and returns this:
785
+
786
+ pt-br de-DE en-US fr pt-br-janeiro pt de en
787
+
788
+ The reason this function has "_strictly" in its name is that when
789
+ you're processing an Accept-Language list according to the RFCs, if
790
+ you interpret the RFCs quite strictly, then you would use
791
+ implicate_supers_strictly, but for normal use (i.e., common-sense use,
792
+ as far as I'm concerned) you'd use implicate_supers.
793
+
794
+ =cut
795
+
796
+ sub implicate_supers {
797
+ my @languages = grep is_language_tag($_), @_;
798
+ my %seen_encoded;
799
+ foreach my $lang (@languages) {
800
+ $seen_encoded{ I18N::LangTags::encode_language_tag($lang) } = 1
801
+ }
802
+
803
+ my(@output_languages);
804
+ foreach my $lang (@languages) {
805
+ push @output_languages, $lang;
806
+ foreach my $s ( I18N::LangTags::super_languages($lang) ) {
807
+ # Note that super_languages returns the longest first.
808
+ last if $seen_encoded{ I18N::LangTags::encode_language_tag($s) };
809
+ push @output_languages, $s;
810
+ }
811
+ }
812
+ return uniq( @output_languages );
813
+
814
+ }
815
+
816
+ sub implicate_supers_strictly {
817
+ my @tags = grep is_language_tag($_), @_;
818
+ return uniq( @_, map super_languages($_), @_ );
819
+ }
820
+
821
+
822
+
823
+ ###########################################################################
824
+ 1;
825
+ __END__
826
+
827
+ =back
828
+
829
+ =head1 ABOUT LOWERCASING
830
+
831
+ I've considered making all the above functions that output language
832
+ tags return all those tags strictly in lowercase. Having all your
833
+ language tags in lowercase does make some things easier. But you
834
+ might as well just lowercase as you like, or call
835
+ C<encode_language_tag($lang1)> where appropriate.
836
+
837
+ =head1 ABOUT UNICODE PLAINTEXT LANGUAGE TAGS
838
+
839
+ In some future version of I18N::LangTags, I plan to include support
840
+ for RFC2482-style language tags -- which are basically just normal
841
+ language tags with their ASCII characters shifted into Plane 14.
842
+
843
+ =head1 SEE ALSO
844
+
845
+ * L<I18N::LangTags::List|I18N::LangTags::List>
846
+
847
+ * RFC 3066, C<L<http://www.ietf.org/rfc/rfc3066.txt>>, "Tags for the
848
+ Identification of Languages". (Obsoletes RFC 1766)
849
+
850
+ * RFC 2277, C<L<http://www.ietf.org/rfc/rfc2277.txt>>, "IETF Policy on
851
+ Character Sets and Languages".
852
+
853
+ * RFC 2231, C<L<http://www.ietf.org/rfc/rfc2231.txt>>, "MIME Parameter
854
+ Value and Encoded Word Extensions: Character Sets, Languages, and
855
+ Continuations".
856
+
857
+ * RFC 2482, C<L<http://www.ietf.org/rfc/rfc2482.txt>>,
858
+ "Language Tagging in Unicode Plain Text".
859
+
860
+ * Locale::Codes, in
861
+ C<L<http://www.perl.com/CPAN/modules/by-module/Locale/>>
862
+
863
+ * ISO 639-2, "Codes for the representation of names of languages",
864
+ including two-letter and three-letter codes,
865
+ C<L<http://www.loc.gov/standards/iso639-2/php/code_list.php>>
866
+
867
+ * The IANA list of registered languages (hopefully up-to-date),
868
+ C<L<http://www.iana.org/assignments/language-tags>>
869
+
870
+ =head1 COPYRIGHT
871
+
872
+ Copyright (c) 1998+ Sean M. Burke. All rights reserved.
873
+
874
+ This library is free software; you can redistribute it and/or
875
+ modify it under the same terms as Perl itself.
876
+
877
+ The programs and documentation in this dist are distributed in
878
+ the hope that they will be useful, but without any warranty; without
879
+ even the implied warranty of merchantability or fitness for a
880
+ particular purpose.
881
+
882
+ =head1 AUTHOR
883
+
884
+ Sean M. Burke C<sburke@cpan.org>
885
+
886
+ =cut
887
+
git/usr/share/perl5/core_perl/IO/Compress.pm ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package IO::Compress;
2
+
3
+ our $VERSION = '2.213' ;
4
+
5
+ =head1 NAME
6
+
7
+ IO::Compress - read/write compressed data in multiple formats
8
+
9
+ =head1 DESCRIPTION
10
+
11
+ This is a stub module. It contains no code.
12
+
13
+ =head1 AUTHOR
14
+
15
+ Paul Marquess F<pmqs@cpan.org>.
16
+
17
+ =head1 COPYRIGHT
18
+
19
+ Copyright (c) 2011-2024 Paul Marquess. All rights reserved.
20
+
21
+ This program is free software; you can redistribute it and/or modify it
22
+ under the same terms as Perl itself.
23
+
24
+ =cut
25
+
26
+
27
+ 1;
git/usr/share/perl5/core_perl/IO/Zlib.pm ADDED
@@ -0,0 +1,740 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # IO::Zlib.pm
2
+ #
3
+ # Copyright (c) 1998-2004 Tom Hughes <tom@compton.nu>.
4
+ # All rights reserved. This program is free software; you can redistribute
5
+ # it and/or modify it under the same terms as Perl itself.
6
+
7
+ package IO::Zlib;
8
+
9
+ =head1 NAME
10
+
11
+ IO::Zlib - IO:: style interface to L<Compress::Zlib>
12
+
13
+ =head1 SYNOPSIS
14
+
15
+ With any version of Perl 5 you can use the basic OO interface:
16
+
17
+ use IO::Zlib;
18
+
19
+ $fh = new IO::Zlib;
20
+ if ($fh->open("file.gz", "rb")) {
21
+ print <$fh>;
22
+ $fh->close;
23
+ }
24
+
25
+ $fh = IO::Zlib->new("file.gz", "wb9");
26
+ if (defined $fh) {
27
+ print $fh "bar\n";
28
+ $fh->close;
29
+ }
30
+
31
+ $fh = IO::Zlib->new("file.gz", "rb");
32
+ if (defined $fh) {
33
+ print <$fh>;
34
+ undef $fh; # automatically closes the file
35
+ }
36
+
37
+ With Perl 5.004 you can also use the TIEHANDLE interface to access
38
+ compressed files just like ordinary files:
39
+
40
+ use IO::Zlib;
41
+
42
+ tie *FILE, 'IO::Zlib', "file.gz", "wb";
43
+ print FILE "line 1\nline2\n";
44
+
45
+ tie *FILE, 'IO::Zlib', "file.gz", "rb";
46
+ while (<FILE>) { print "LINE: ", $_ };
47
+
48
+ =head1 DESCRIPTION
49
+
50
+ C<IO::Zlib> provides an IO:: style interface to L<Compress::Zlib> and
51
+ hence to gzip/zlib compressed files. It provides many of the same methods
52
+ as the L<IO::Handle> interface.
53
+
54
+ Starting from IO::Zlib version 1.02, IO::Zlib can also use an
55
+ external F<gzip> command. The default behaviour is to try to use
56
+ an external F<gzip> if no C<Compress::Zlib> can be loaded, unless
57
+ explicitly disabled by
58
+
59
+ use IO::Zlib qw(:gzip_external 0);
60
+
61
+ If explicitly enabled by
62
+
63
+ use IO::Zlib qw(:gzip_external 1);
64
+
65
+ then the external F<gzip> is used B<instead> of C<Compress::Zlib>.
66
+
67
+ =head1 CONSTRUCTOR
68
+
69
+ =over 4
70
+
71
+ =item new ( [ARGS] )
72
+
73
+ Creates an C<IO::Zlib> object. If it receives any parameters, they are
74
+ passed to the method C<open>; if the open fails, the object is destroyed.
75
+ Otherwise, it is returned to the caller.
76
+
77
+ =back
78
+
79
+ =head1 OBJECT METHODS
80
+
81
+ =over 4
82
+
83
+ =item open ( FILENAME, MODE )
84
+
85
+ C<open> takes two arguments. The first is the name of the file to open
86
+ and the second is the open mode. The mode can be anything acceptable to
87
+ L<Compress::Zlib> and by extension anything acceptable to I<zlib> (that
88
+ basically means POSIX fopen() style mode strings plus an optional number
89
+ to indicate the compression level).
90
+
91
+ =item opened
92
+
93
+ Returns true if the object currently refers to a opened file.
94
+
95
+ =item close
96
+
97
+ Close the file associated with the object and disassociate
98
+ the file from the handle.
99
+ Done automatically on destroy.
100
+
101
+ =item getc
102
+
103
+ Return the next character from the file, or undef if none remain.
104
+
105
+ =item getline
106
+
107
+ Return the next line from the file, or undef on end of string.
108
+ Can safely be called in an array context.
109
+ Currently ignores $/ ($INPUT_RECORD_SEPARATOR or $RS when L<English>
110
+ is in use) and treats lines as delimited by "\n".
111
+
112
+ =item getlines
113
+
114
+ Get all remaining lines from the file.
115
+ It will croak() if accidentally called in a scalar context.
116
+
117
+ =item print ( ARGS... )
118
+
119
+ Print ARGS to the file.
120
+
121
+ =item read ( BUF, NBYTES, [OFFSET] )
122
+
123
+ Read some bytes from the file.
124
+ Returns the number of bytes actually read, 0 on end-of-file, undef on error.
125
+
126
+ =item eof
127
+
128
+ Returns true if the handle is currently positioned at end of file?
129
+
130
+ =item seek ( OFFSET, WHENCE )
131
+
132
+ Seek to a given position in the stream.
133
+ Not yet supported.
134
+
135
+ =item tell
136
+
137
+ Return the current position in the stream, as a numeric offset.
138
+ Not yet supported.
139
+
140
+ =item setpos ( POS )
141
+
142
+ Set the current position, using the opaque value returned by C<getpos()>.
143
+ Not yet supported.
144
+
145
+ =item getpos ( POS )
146
+
147
+ Return the current position in the string, as an opaque object.
148
+ Not yet supported.
149
+
150
+ =back
151
+
152
+ =head1 USING THE EXTERNAL GZIP
153
+
154
+ If the external F<gzip> is used, the following C<open>s are used:
155
+
156
+ open(FH, "gzip -dc $filename |") # for read opens
157
+ open(FH, " | gzip > $filename") # for write opens
158
+
159
+ You can modify the 'commands' for example to hardwire
160
+ an absolute path by e.g.
161
+
162
+ use IO::Zlib ':gzip_read_open' => '/some/where/gunzip -c %s |';
163
+ use IO::Zlib ':gzip_write_open' => '| /some/where/gzip.exe > %s';
164
+
165
+ The C<%s> is expanded to be the filename (C<sprintf> is used, so be
166
+ careful to escape any other C<%> signs). The 'commands' are checked
167
+ for sanity - they must contain the C<%s>, and the read open must end
168
+ with the pipe sign, and the write open must begin with the pipe sign.
169
+
170
+ =head1 CLASS METHODS
171
+
172
+ =over 4
173
+
174
+ =item has_Compress_Zlib
175
+
176
+ Returns true if C<Compress::Zlib> is available. Note that this does
177
+ not mean that C<Compress::Zlib> is being used: see L</gzip_external>
178
+ and L<gzip_used>.
179
+
180
+ =item gzip_external
181
+
182
+ Undef if an external F<gzip> B<can> be used if C<Compress::Zlib> is
183
+ not available (see L</has_Compress_Zlib>), true if an external F<gzip>
184
+ is explicitly used, false if an external F<gzip> must not be used.
185
+ See L</gzip_used>.
186
+
187
+ =item gzip_used
188
+
189
+ True if an external F<gzip> is being used, false if not.
190
+
191
+ =item gzip_read_open
192
+
193
+ Return the 'command' being used for opening a file for reading using an
194
+ external F<gzip>.
195
+
196
+ =item gzip_write_open
197
+
198
+ Return the 'command' being used for opening a file for writing using an
199
+ external F<gzip>.
200
+
201
+ =back
202
+
203
+ =head1 DIAGNOSTICS
204
+
205
+ =over 4
206
+
207
+ =item IO::Zlib::getlines: must be called in list context
208
+
209
+ If you want read lines, you must read in list context.
210
+
211
+ =item IO::Zlib::gzopen_external: mode '...' is illegal
212
+
213
+ Use only modes 'rb' or 'wb' or /wb[1-9]/.
214
+
215
+ =item IO::Zlib::import: '...' is illegal
216
+
217
+ The known import symbols are the C<:gzip_external>, C<:gzip_read_open>,
218
+ and C<:gzip_write_open>. Anything else is not recognized.
219
+
220
+ =item IO::Zlib::import: ':gzip_external' requires an argument
221
+
222
+ The C<:gzip_external> requires one boolean argument.
223
+
224
+ =item IO::Zlib::import: 'gzip_read_open' requires an argument
225
+
226
+ The C<:gzip_external> requires one string argument.
227
+
228
+ =item IO::Zlib::import: 'gzip_read' '...' is illegal
229
+
230
+ The C<:gzip_read_open> argument must end with the pipe sign (|)
231
+ and have the C<%s> for the filename. See L</"USING THE EXTERNAL GZIP">.
232
+
233
+ =item IO::Zlib::import: 'gzip_write_open' requires an argument
234
+
235
+ The C<:gzip_external> requires one string argument.
236
+
237
+ =item IO::Zlib::import: 'gzip_write_open' '...' is illegal
238
+
239
+ The C<:gzip_write_open> argument must begin with the pipe sign (|)
240
+ and have the C<%s> for the filename. An output redirect (>) is also
241
+ often a good idea, depending on your operating system shell syntax.
242
+ See L</"USING THE EXTERNAL GZIP">.
243
+
244
+ =item IO::Zlib::import: no Compress::Zlib and no external gzip
245
+
246
+ Given that we failed to load C<Compress::Zlib> and that the use of
247
+ an external F<gzip> was disabled, IO::Zlib has not much chance of working.
248
+
249
+ =item IO::Zlib::open: needs a filename
250
+
251
+ No filename, no open.
252
+
253
+ =item IO::Zlib::READ: NBYTES must be specified
254
+
255
+ We must know how much to read.
256
+
257
+ =item IO::Zlib::WRITE: too long LENGTH
258
+
259
+ The LENGTH must be less than or equal to the buffer size.
260
+
261
+ =back
262
+
263
+ =head1 SEE ALSO
264
+
265
+ L<perlfunc>,
266
+ L<perlop/"I/O Operators">,
267
+ L<IO::Handle>,
268
+ L<Compress::Zlib>
269
+
270
+ =head1 HISTORY
271
+
272
+ Created by Tom Hughes E<lt>F<tom@compton.nu>E<gt>.
273
+
274
+ Support for external gzip added by Jarkko Hietaniemi E<lt>F<jhi@iki.fi>E<gt>.
275
+
276
+ =head1 COPYRIGHT
277
+
278
+ Copyright (c) 1998-2004 Tom Hughes E<lt>F<tom@compton.nu>E<gt>.
279
+ All rights reserved. This program is free software; you can redistribute
280
+ it and/or modify it under the same terms as Perl itself.
281
+
282
+ =cut
283
+
284
+ require 5.006;
285
+
286
+ use strict;
287
+ use warnings;
288
+
289
+ use Carp;
290
+ use Fcntl qw(SEEK_SET);
291
+ use Symbol;
292
+ use Tie::Handle;
293
+
294
+ our $VERSION = "1.15";
295
+ our $AUTOLOAD;
296
+ our @ISA = qw(Tie::Handle);
297
+
298
+ my $has_Compress_Zlib;
299
+ my $gzip_external;
300
+ my $gzip_used;
301
+ my $gzip_read_open = "gzip -dc %s |";
302
+ my $gzip_write_open = "| gzip > %s";
303
+ my $aliased;
304
+
305
+ BEGIN {
306
+ eval { require Compress::Zlib };
307
+ $has_Compress_Zlib = $@ || $Compress::Zlib::VERSION < 2.000 ? 0 : 1;
308
+ }
309
+
310
+ sub has_Compress_Zlib
311
+ {
312
+ $has_Compress_Zlib;
313
+ }
314
+
315
+ sub gzip_external
316
+ {
317
+ $gzip_external;
318
+ }
319
+
320
+ sub gzip_used
321
+ {
322
+ $gzip_used;
323
+ }
324
+
325
+ sub gzip_read_open
326
+ {
327
+ $gzip_read_open;
328
+ }
329
+
330
+ sub gzip_write_open
331
+ {
332
+ $gzip_write_open;
333
+ }
334
+
335
+ sub can_gunzip
336
+ {
337
+ $has_Compress_Zlib || $gzip_external;
338
+ }
339
+
340
+ sub _import
341
+ {
342
+ my $import = shift;
343
+
344
+ while (@_)
345
+ {
346
+ if ($_[0] eq ':gzip_external')
347
+ {
348
+ shift;
349
+
350
+ if (@_)
351
+ {
352
+ $gzip_external = shift;
353
+ }
354
+ else
355
+ {
356
+ croak "$import: ':gzip_external' requires an argument";
357
+ }
358
+ }
359
+ elsif ($_[0] eq ':gzip_read_open')
360
+ {
361
+ shift;
362
+
363
+ if (@_)
364
+ {
365
+ $gzip_read_open = shift;
366
+
367
+ croak "$import: ':gzip_read_open' '$gzip_read_open' is illegal"
368
+ unless $gzip_read_open =~ /^.+%s.+\|\s*$/;
369
+ }
370
+ else
371
+ {
372
+ croak "$import: ':gzip_read_open' requires an argument";
373
+ }
374
+ }
375
+ elsif ($_[0] eq ':gzip_write_open')
376
+ {
377
+ shift;
378
+
379
+ if (@_)
380
+ {
381
+ $gzip_write_open = shift;
382
+
383
+ croak "$import: ':gzip_write_open' '$gzip_read_open' is illegal"
384
+ unless $gzip_write_open =~ /^\s*\|.+%s.*$/;
385
+ }
386
+ else
387
+ {
388
+ croak "$import: ':gzip_write_open' requires an argument";
389
+ }
390
+ }
391
+ else
392
+ {
393
+ last;
394
+ }
395
+ }
396
+
397
+ return @_;
398
+ }
399
+
400
+ sub _alias
401
+ {
402
+ my $import = shift;
403
+
404
+ if ($gzip_external || (!$has_Compress_Zlib && !defined($gzip_external)))
405
+ {
406
+ require IO::Handle;
407
+
408
+ undef *gzopen;
409
+ *gzopen = \&gzopen_external;
410
+
411
+ *IO::Handle::gzread = \&gzread_external;
412
+ *IO::Handle::gzwrite = \&gzwrite_external;
413
+ *IO::Handle::gzreadline = \&gzreadline_external;
414
+ *IO::Handle::gzeof = \&gzeof_external;
415
+ *IO::Handle::gzclose = \&gzclose_external;
416
+
417
+ $gzip_used = 1;
418
+ }
419
+ elsif ($has_Compress_Zlib)
420
+ {
421
+ *gzopen = \&Compress::Zlib::gzopen;
422
+ *gzread = \&Compress::Zlib::gzread;
423
+ *gzwrite = \&Compress::Zlib::gzwrite;
424
+ *gzreadline = \&Compress::Zlib::gzreadline;
425
+ *gzeof = \&Compress::Zlib::gzeof;
426
+ }
427
+ else
428
+ {
429
+ croak "$import: no Compress::Zlib and no external gzip";
430
+ }
431
+
432
+ $aliased = 1;
433
+ }
434
+
435
+ sub import
436
+ {
437
+ my $class = shift;
438
+ my $import = "IO::Zlib::import";
439
+
440
+ if (@_)
441
+ {
442
+ if (_import($import, @_))
443
+ {
444
+ croak "$import: '@_' is illegal";
445
+ }
446
+ }
447
+
448
+ _alias($import);
449
+ }
450
+
451
+ sub TIEHANDLE
452
+ {
453
+ my $class = shift;
454
+ my @args = @_;
455
+
456
+ my $self = bless {}, $class;
457
+
458
+ return @args ? $self->OPEN(@args) : $self;
459
+ }
460
+
461
+ sub DESTROY
462
+ {
463
+ }
464
+
465
+ sub OPEN
466
+ {
467
+ my $self = shift;
468
+ my $filename = shift;
469
+ my $mode = shift;
470
+
471
+ croak "IO::Zlib::open: needs a filename" unless defined($filename);
472
+
473
+ $self->{'file'} = gzopen($filename,$mode);
474
+
475
+ return defined($self->{'file'}) ? $self : undef;
476
+ }
477
+
478
+ sub CLOSE
479
+ {
480
+ my $self = shift;
481
+
482
+ return undef unless defined($self->{'file'});
483
+
484
+ my $status = $self->{'file'}->gzclose();
485
+
486
+ delete $self->{'file'};
487
+
488
+ return ($status == 0) ? 1 : undef;
489
+ }
490
+
491
+ sub READ
492
+ {
493
+ my $self = shift;
494
+ my $bufref = \$_[0];
495
+ my $nbytes = $_[1];
496
+ my $offset = $_[2] || 0;
497
+
498
+ croak "IO::Zlib::READ: NBYTES must be specified" unless defined($nbytes);
499
+
500
+ $$bufref = "" unless defined($$bufref);
501
+
502
+ my $bytesread = $self->{'file'}->gzread(substr($$bufref,$offset),$nbytes);
503
+
504
+ return undef if $bytesread < 0;
505
+
506
+ return $bytesread;
507
+ }
508
+
509
+ sub READLINE
510
+ {
511
+ my $self = shift;
512
+
513
+ my $line;
514
+
515
+ return () if $self->{'file'}->gzreadline($line) <= 0;
516
+
517
+ return $line unless wantarray;
518
+
519
+ my @lines = $line;
520
+
521
+ while ($self->{'file'}->gzreadline($line) > 0)
522
+ {
523
+ push @lines, $line;
524
+ }
525
+
526
+ return @lines;
527
+ }
528
+
529
+ sub WRITE
530
+ {
531
+ my $self = shift;
532
+ my $buf = shift;
533
+ my $length = shift;
534
+ my $offset = shift;
535
+
536
+ croak "IO::Zlib::WRITE: too long LENGTH" unless $offset + $length <= length($buf);
537
+
538
+ return $self->{'file'}->gzwrite(substr($buf,$offset,$length));
539
+ }
540
+
541
+ sub EOF
542
+ {
543
+ my $self = shift;
544
+
545
+ return $self->{'file'}->gzeof();
546
+ }
547
+
548
+ sub FILENO
549
+ {
550
+ return undef;
551
+ }
552
+
553
+ sub new
554
+ {
555
+ my $class = shift;
556
+ my @args = @_;
557
+
558
+ _alias("new", @_) unless $aliased; # Some call new IO::Zlib directly...
559
+
560
+ my $self = gensym();
561
+
562
+ tie *{$self}, $class, @args;
563
+
564
+ return tied(${$self}) ? bless $self, $class : undef;
565
+ }
566
+
567
+ sub getline
568
+ {
569
+ my $self = shift;
570
+
571
+ return scalar tied(*{$self})->READLINE();
572
+ }
573
+
574
+ sub getlines
575
+ {
576
+ my $self = shift;
577
+
578
+ croak "IO::Zlib::getlines: must be called in list context"
579
+ unless wantarray;
580
+
581
+ return tied(*{$self})->READLINE();
582
+ }
583
+
584
+ sub opened
585
+ {
586
+ my $self = shift;
587
+
588
+ return defined tied(*{$self})->{'file'};
589
+ }
590
+
591
+ sub AUTOLOAD
592
+ {
593
+ my $self = shift;
594
+
595
+ $AUTOLOAD =~ s/.*:://;
596
+ $AUTOLOAD =~ tr/a-z/A-Z/;
597
+
598
+ return tied(*{$self})->$AUTOLOAD(@_);
599
+ }
600
+
601
+ sub gzopen_external
602
+ {
603
+ my $filename = shift;
604
+ my $mode = shift;
605
+ my $fh = IO::Handle->new();
606
+
607
+ if ($mode =~ /r/)
608
+ {
609
+ # Because someone will try to read ungzipped files
610
+ # with this we peek and verify the signature. Yes,
611
+ # this means that we open the file twice (if it is
612
+ # gzipped).
613
+ # Plenty of race conditions exist in this code, but
614
+ # the alternative would be to capture the stderr of
615
+ # gzip and parse it, which would be a portability nightmare.
616
+ if (-e $filename && open($fh, $filename))
617
+ {
618
+ binmode $fh;
619
+
620
+ my $sig;
621
+ my $rdb = read($fh, $sig, 2);
622
+
623
+ if ($rdb == 2 && $sig eq "\x1F\x8B")
624
+ {
625
+ my $ropen = sprintf($gzip_read_open, $filename);
626
+
627
+ if (open($fh, $ropen))
628
+ {
629
+ binmode $fh;
630
+
631
+ return $fh;
632
+ }
633
+ else
634
+ {
635
+ return undef;
636
+ }
637
+ }
638
+
639
+ seek($fh, 0, SEEK_SET) or
640
+ die "IO::Zlib: open('$filename', 'r'): seek: $!";
641
+
642
+ return $fh;
643
+ }
644
+ else
645
+ {
646
+ return undef;
647
+ }
648
+ }
649
+ elsif ($mode =~ /w/)
650
+ {
651
+ my $level = $mode =~ /([1-9])/ ? "-$1" : "";
652
+
653
+ # To maximize portability we would need to open
654
+ # two filehandles here, one for "| gzip $level"
655
+ # and another for "> $filename", and then when
656
+ # writing copy bytes from the first to the second.
657
+ # We are using IO::Handle objects for now, however,
658
+ # and they can only contain one stream at a time.
659
+ my $wopen = sprintf($gzip_write_open, $filename);
660
+
661
+ if (open($fh, $wopen))
662
+ {
663
+ $fh->autoflush(1);
664
+ binmode $fh;
665
+
666
+ return $fh;
667
+ }
668
+ else
669
+ {
670
+ return undef;
671
+ }
672
+ }
673
+ else
674
+ {
675
+ croak "IO::Zlib::gzopen_external: mode '$mode' is illegal";
676
+ }
677
+
678
+ return undef;
679
+ }
680
+
681
+ sub gzread_external
682
+ {
683
+ my $file = shift;
684
+ my $bufref = \$_[0];
685
+ my $nbytes = $_[1] || 4096;
686
+
687
+ # Use read() instead of sysread() because people may
688
+ # mix reads and readlines, and we don't want to mess
689
+ # the stdio buffering. See also gzreadline_external()
690
+ # and gzwrite_external().
691
+ my $nread = read($file, $$bufref, $nbytes);
692
+
693
+ return defined $nread ? $nread : -1;
694
+ }
695
+
696
+ sub gzwrite_external
697
+ {
698
+ my $file = shift;
699
+ my $buf = shift;
700
+
701
+ # Using syswrite() is okay (cf. gzread_external())
702
+ # since the bytes leave this process and buffering
703
+ # is therefore not an issue.
704
+ my $nwrote = syswrite($file, $buf);
705
+
706
+ return defined $nwrote ? $nwrote : -1;
707
+ }
708
+
709
+ sub gzreadline_external
710
+ {
711
+ my $file = shift;
712
+ my $bufref = \$_[0];
713
+
714
+ # See the comment in gzread_external().
715
+ $$bufref = readline($file);
716
+
717
+ return defined $$bufref ? length($$bufref) : -1;
718
+ }
719
+
720
+ sub gzeof_external
721
+ {
722
+ my $file = shift;
723
+
724
+ return eof($file);
725
+ }
726
+
727
+ sub gzclose_external
728
+ {
729
+ my $file = shift;
730
+
731
+ close($file);
732
+
733
+ # I am not entirely certain why this is needed but it seems
734
+ # the above close() always fails (as if the stream would have
735
+ # been already closed - something to do with using external
736
+ # processes via pipes?)
737
+ return 0;
738
+ }
739
+
740
+ 1;
git/usr/share/perl5/core_perl/IPC/Cmd.pm ADDED
@@ -0,0 +1,2187 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package IPC::Cmd;
2
+
3
+ use strict;
4
+
5
+ BEGIN {
6
+
7
+ use constant IS_VMS => $^O eq 'VMS' ? 1 : 0;
8
+ use constant IS_WIN32 => $^O eq 'MSWin32' ? 1 : 0;
9
+ use constant IS_HPUX => $^O eq 'hpux' ? 1 : 0;
10
+ use constant IS_WIN98 => (IS_WIN32 and !Win32::IsWinNT()) ? 1 : 0;
11
+ use constant ALARM_CLASS => __PACKAGE__ . '::TimeOut';
12
+ use constant SPECIAL_CHARS => qw[< > | &];
13
+ use constant QUOTE => do { IS_WIN32 ? q["] : q['] };
14
+
15
+ use Exporter ();
16
+ use vars qw[ @ISA $VERSION @EXPORT_OK $VERBOSE $DEBUG
17
+ $USE_IPC_RUN $USE_IPC_OPEN3 $CAN_USE_RUN_FORKED $WARN
18
+ $INSTANCES $ALLOW_NULL_ARGS
19
+ $HAVE_MONOTONIC
20
+ ];
21
+
22
+ $VERSION = '1.04';
23
+ $VERBOSE = 0;
24
+ $DEBUG = 0;
25
+ $WARN = 1;
26
+ $USE_IPC_RUN = IS_WIN32 && !IS_WIN98;
27
+ $USE_IPC_OPEN3 = not IS_VMS;
28
+ $ALLOW_NULL_ARGS = 0;
29
+
30
+ $CAN_USE_RUN_FORKED = 0;
31
+ eval {
32
+ require POSIX; POSIX->import();
33
+ require IPC::Open3; IPC::Open3->import();
34
+ require IO::Select; IO::Select->import();
35
+ require IO::Handle; IO::Handle->import();
36
+ require FileHandle; FileHandle->import();
37
+ require Socket;
38
+ require Time::HiRes; Time::HiRes->import();
39
+ require Win32 if IS_WIN32;
40
+ };
41
+ $CAN_USE_RUN_FORKED = $@ || !IS_VMS && !IS_WIN32;
42
+
43
+ eval {
44
+ my $wait_start_time = Time::HiRes::clock_gettime(&Time::HiRes::CLOCK_MONOTONIC);
45
+ };
46
+ if ($@) {
47
+ $HAVE_MONOTONIC = 0;
48
+ }
49
+ else {
50
+ $HAVE_MONOTONIC = 1;
51
+ }
52
+
53
+ @ISA = qw[Exporter];
54
+ @EXPORT_OK = qw[can_run run run_forked QUOTE];
55
+ }
56
+
57
+ require Carp;
58
+ use File::Spec;
59
+ use Params::Check qw[check];
60
+ use Text::ParseWords (); # import ONLY if needed!
61
+ use Module::Load::Conditional qw[can_load];
62
+ use Locale::Maketext::Simple Style => 'gettext';
63
+
64
+ local $Module::Load::Conditional::FORCE_SAFE_INC = 1;
65
+
66
+ =pod
67
+
68
+ =head1 NAME
69
+
70
+ IPC::Cmd - finding and running system commands made easy
71
+
72
+ =head1 SYNOPSIS
73
+
74
+ use IPC::Cmd qw[can_run run run_forked];
75
+
76
+ my $full_path = can_run('wget') or warn 'wget is not installed!';
77
+
78
+ ### commands can be arrayrefs or strings ###
79
+ my $cmd = "$full_path -b theregister.co.uk";
80
+ my $cmd = [$full_path, '-b', 'theregister.co.uk'];
81
+
82
+ ### in scalar context ###
83
+ my $buffer;
84
+ if( scalar run( command => $cmd,
85
+ verbose => 0,
86
+ buffer => \$buffer,
87
+ timeout => 20 )
88
+ ) {
89
+ print "fetched webpage successfully: $buffer\n";
90
+ }
91
+
92
+
93
+ ### in list context ###
94
+ my( $success, $error_message, $full_buf, $stdout_buf, $stderr_buf ) =
95
+ run( command => $cmd, verbose => 0 );
96
+
97
+ if( $success ) {
98
+ print "this is what the command printed:\n";
99
+ print join "", @$full_buf;
100
+ }
101
+
102
+ ### run_forked example ###
103
+ my $result = run_forked("$full_path -q -O - theregister.co.uk", {'timeout' => 20});
104
+ if ($result->{'exit_code'} eq 0 && !$result->{'timeout'}) {
105
+ print "this is what wget returned:\n";
106
+ print $result->{'stdout'};
107
+ }
108
+
109
+ ### check for features
110
+ print "IPC::Open3 available: " . IPC::Cmd->can_use_ipc_open3;
111
+ print "IPC::Run available: " . IPC::Cmd->can_use_ipc_run;
112
+ print "Can capture buffer: " . IPC::Cmd->can_capture_buffer;
113
+
114
+ ### don't have IPC::Cmd be verbose, ie don't print to stdout or
115
+ ### stderr when running commands -- default is '0'
116
+ $IPC::Cmd::VERBOSE = 0;
117
+
118
+
119
+ =head1 DESCRIPTION
120
+
121
+ IPC::Cmd allows you to run commands platform independently,
122
+ interactively if desired, but have them still work.
123
+
124
+ The C<can_run> function can tell you if a certain binary is installed
125
+ and if so where, whereas the C<run> function can actually execute any
126
+ of the commands you give it and give you a clear return value, as well
127
+ as adhere to your verbosity settings.
128
+
129
+ =head1 CLASS METHODS
130
+
131
+ =head2 $ipc_run_version = IPC::Cmd->can_use_ipc_run( [VERBOSE] )
132
+
133
+ Utility function that tells you if C<IPC::Run> is available.
134
+ If the C<verbose> flag is passed, it will print diagnostic messages
135
+ if L<IPC::Run> can not be found or loaded.
136
+
137
+ =cut
138
+
139
+
140
+ sub can_use_ipc_run {
141
+ my $self = shift;
142
+ my $verbose = shift || 0;
143
+
144
+ ### IPC::Run doesn't run on win98
145
+ return if IS_WIN98;
146
+
147
+ ### if we don't have ipc::run, we obviously can't use it.
148
+ return unless can_load(
149
+ modules => { 'IPC::Run' => '0.55' },
150
+ verbose => ($WARN && $verbose),
151
+ );
152
+
153
+ ### otherwise, we're good to go
154
+ return $IPC::Run::VERSION;
155
+ }
156
+
157
+ =head2 $ipc_open3_version = IPC::Cmd->can_use_ipc_open3( [VERBOSE] )
158
+
159
+ Utility function that tells you if C<IPC::Open3> is available.
160
+ If the verbose flag is passed, it will print diagnostic messages
161
+ if C<IPC::Open3> can not be found or loaded.
162
+
163
+ =cut
164
+
165
+
166
+ sub can_use_ipc_open3 {
167
+ my $self = shift;
168
+ my $verbose = shift || 0;
169
+
170
+ ### IPC::Open3 is not working on VMS because of a lack of fork.
171
+ return if IS_VMS;
172
+
173
+ ### IPC::Open3 works on every non-VMS platform, but it can't
174
+ ### capture buffers on win32 :(
175
+ return unless can_load(
176
+ modules => { map {$_ => '0.0'} qw|IPC::Open3 IO::Select Symbol| },
177
+ verbose => ($WARN && $verbose),
178
+ );
179
+
180
+ return $IPC::Open3::VERSION;
181
+ }
182
+
183
+ =head2 $bool = IPC::Cmd->can_capture_buffer
184
+
185
+ Utility function that tells you if C<IPC::Cmd> is capable of
186
+ capturing buffers in it's current configuration.
187
+
188
+ =cut
189
+
190
+ sub can_capture_buffer {
191
+ my $self = shift;
192
+
193
+ return 1 if $USE_IPC_RUN && $self->can_use_ipc_run;
194
+ return 1 if $USE_IPC_OPEN3 && $self->can_use_ipc_open3;
195
+ return;
196
+ }
197
+
198
+ =head2 $bool = IPC::Cmd->can_use_run_forked
199
+
200
+ Utility function that tells you if C<IPC::Cmd> is capable of
201
+ providing C<run_forked> on the current platform.
202
+
203
+ =head1 FUNCTIONS
204
+
205
+ =head2 $path = can_run( PROGRAM );
206
+
207
+ C<can_run> takes only one argument: the name of a binary you wish
208
+ to locate. C<can_run> works much like the unix binary C<which> or the bash
209
+ command C<type>, which scans through your path, looking for the requested
210
+ binary.
211
+
212
+ Unlike C<which> and C<type>, this function is platform independent and
213
+ will also work on, for example, Win32.
214
+
215
+ If called in a scalar context it will return the full path to the binary
216
+ you asked for if it was found, or C<undef> if it was not.
217
+
218
+ If called in a list context and the global variable C<$INSTANCES> is a true
219
+ value, it will return a list of the full paths to instances
220
+ of the binary where found in C<PATH>, or an empty list if it was not found.
221
+
222
+ =cut
223
+
224
+ sub can_run {
225
+ my $command = shift;
226
+
227
+ # a lot of VMS executables have a symbol defined
228
+ # check those first
229
+ if ( $^O eq 'VMS' ) {
230
+ require VMS::DCLsym;
231
+ my $syms = VMS::DCLsym->new;
232
+ return $command if scalar $syms->getsym( uc $command );
233
+ }
234
+
235
+ require File::Spec;
236
+ require ExtUtils::MakeMaker;
237
+
238
+ my @possibles;
239
+
240
+ if( File::Spec->file_name_is_absolute($command) ) {
241
+ return MM->maybe_command($command);
242
+
243
+ } else {
244
+ for my $dir (
245
+ File::Spec->path,
246
+ ( IS_WIN32 ? File::Spec->curdir : () )
247
+ ) {
248
+ next if ! $dir || ! -d $dir;
249
+ my $abs = File::Spec->catfile( IS_WIN32 ? Win32::GetShortPathName( $dir ) : $dir, $command);
250
+ push @possibles, $abs if $abs = MM->maybe_command($abs);
251
+ }
252
+ }
253
+ return @possibles if wantarray and $INSTANCES;
254
+ return shift @possibles;
255
+ }
256
+
257
+ =head2 $ok | ($ok, $err, $full_buf, $stdout_buff, $stderr_buff) = run( command => COMMAND, [verbose => BOOL, buffer => \$SCALAR, timeout => DIGIT] );
258
+
259
+ C<run> takes 4 arguments:
260
+
261
+ =over 4
262
+
263
+ =item command
264
+
265
+ This is the command to execute. It may be either a string or an array
266
+ reference.
267
+ This is a required argument.
268
+
269
+ See L<"Caveats"> for remarks on how commands are parsed and their
270
+ limitations.
271
+
272
+ =item verbose
273
+
274
+ This controls whether all output of a command should also be printed
275
+ to STDOUT/STDERR or should only be trapped in buffers (NOTE: buffers
276
+ require L<IPC::Run> to be installed, or your system able to work with
277
+ L<IPC::Open3>).
278
+
279
+ It will default to the global setting of C<$IPC::Cmd::VERBOSE>,
280
+ which by default is 0.
281
+
282
+ =item buffer
283
+
284
+ This will hold all the output of a command. It needs to be a reference
285
+ to a scalar.
286
+ Note that this will hold both the STDOUT and STDERR messages, and you
287
+ have no way of telling which is which.
288
+ If you require this distinction, run the C<run> command in list context
289
+ and inspect the individual buffers.
290
+
291
+ Of course, this requires that the underlying call supports buffers. See
292
+ the note on buffers above.
293
+
294
+ =item timeout
295
+
296
+ Sets the maximum time the command is allowed to run before aborting,
297
+ using the built-in C<alarm()> call. If the timeout is triggered, the
298
+ C<errorcode> in the return value will be set to an object of the
299
+ C<IPC::Cmd::TimeOut> class. See the L<"error message"> section below for
300
+ details.
301
+
302
+ Defaults to C<0>, meaning no timeout is set.
303
+
304
+ =back
305
+
306
+ C<run> will return a simple C<true> or C<false> when called in scalar
307
+ context.
308
+ In list context, you will be returned a list of the following items:
309
+
310
+ =over 4
311
+
312
+ =item success
313
+
314
+ A simple boolean indicating if the command executed without errors or
315
+ not.
316
+
317
+ =item error message
318
+
319
+ If the first element of the return value (C<success>) was 0, then some
320
+ error occurred. This second element is the error message the command
321
+ you requested exited with, if available. This is generally a pretty
322
+ printed value of C<$?> or C<$@>. See C<perldoc perlvar> for details on
323
+ what they can contain.
324
+ If the error was a timeout, the C<error message> will be prefixed with
325
+ the string C<IPC::Cmd::TimeOut>, the timeout class.
326
+
327
+ =item full_buffer
328
+
329
+ This is an array reference containing all the output the command
330
+ generated.
331
+ Note that buffers are only available if you have L<IPC::Run> installed,
332
+ or if your system is able to work with L<IPC::Open3> -- see below).
333
+ Otherwise, this element will be C<undef>.
334
+
335
+ =item out_buffer
336
+
337
+ This is an array reference containing all the output sent to STDOUT the
338
+ command generated. The notes from L<"full_buffer"> apply.
339
+
340
+ =item error_buffer
341
+
342
+ This is an arrayreference containing all the output sent to STDERR the
343
+ command generated. The notes from L<"full_buffer"> apply.
344
+
345
+
346
+ =back
347
+
348
+ See the L<"HOW IT WORKS"> section below to see how C<IPC::Cmd> decides
349
+ what modules or function calls to use when issuing a command.
350
+
351
+ =cut
352
+
353
+ { my @acc = qw[ok error _fds];
354
+
355
+ ### autogenerate accessors ###
356
+ for my $key ( @acc ) {
357
+ no strict 'refs';
358
+ *{__PACKAGE__."::$key"} = sub {
359
+ $_[0]->{$key} = $_[1] if @_ > 1;
360
+ return $_[0]->{$key};
361
+ }
362
+ }
363
+ }
364
+
365
+ sub can_use_run_forked {
366
+ return $CAN_USE_RUN_FORKED eq "1";
367
+ }
368
+
369
+ sub get_monotonic_time {
370
+ if ($HAVE_MONOTONIC) {
371
+ return Time::HiRes::clock_gettime(&Time::HiRes::CLOCK_MONOTONIC);
372
+ }
373
+ else {
374
+ return time();
375
+ }
376
+ }
377
+
378
+ sub adjust_monotonic_start_time {
379
+ my ($ref_vars, $now, $previous) = @_;
380
+
381
+ # workaround only for those systems which don't have
382
+ # Time::HiRes::CLOCK_MONOTONIC (Mac OSX in particular)
383
+ return if $HAVE_MONOTONIC;
384
+
385
+ # don't have previous monotonic value (only happens once
386
+ # in the beginning of the program execution)
387
+ return unless $previous;
388
+
389
+ my $time_diff = $now - $previous;
390
+
391
+ # adjust previously saved time with the skew value which is
392
+ # either negative when clock moved back or more than 5 seconds --
393
+ # assuming that event loop does happen more often than once
394
+ # per five seconds, which might not be always true (!) but
395
+ # hopefully that's ok, because it's just a workaround
396
+ if ($time_diff > 5 || $time_diff < 0) {
397
+ foreach my $ref_var (@{$ref_vars}) {
398
+ if (defined($$ref_var)) {
399
+ $$ref_var = $$ref_var + $time_diff;
400
+ }
401
+ }
402
+ }
403
+ }
404
+
405
+ sub uninstall_signals {
406
+ return unless defined($IPC::Cmd::{'__old_signals'});
407
+
408
+ foreach my $sig_name (keys %{$IPC::Cmd::{'__old_signals'}}) {
409
+ $SIG{$sig_name} = $IPC::Cmd::{'__old_signals'}->{$sig_name};
410
+ }
411
+ }
412
+
413
+ # incompatible with POSIX::SigAction
414
+ #
415
+ sub install_layered_signal {
416
+ my ($s, $handler_code) = @_;
417
+
418
+ my %available_signals = map {$_ => 1} keys %SIG;
419
+
420
+ Carp::confess("install_layered_signal got nonexistent signal name [$s]")
421
+ unless defined($available_signals{$s});
422
+ Carp::confess("install_layered_signal expects coderef")
423
+ if !ref($handler_code) || ref($handler_code) ne 'CODE';
424
+
425
+ $IPC::Cmd::{'__old_signals'} = {}
426
+ unless defined($IPC::Cmd::{'__old_signals'});
427
+ $IPC::Cmd::{'__old_signals'}->{$s} = $SIG{$s};
428
+
429
+ my $previous_handler = $SIG{$s};
430
+
431
+ my $sig_handler = sub {
432
+ my ($called_sig_name, @sig_param) = @_;
433
+
434
+ # $s is a closure referring to real signal name
435
+ # for which this handler is being installed.
436
+ # it is used to distinguish between
437
+ # real signal handlers and aliased signal handlers
438
+ my $signal_name = $s;
439
+
440
+ # $called_sig_name is a signal name which
441
+ # was passed to this signal handler;
442
+ # it doesn't equal $signal_name in case
443
+ # some signal handlers in %SIG point
444
+ # to other signal handler (CHLD and CLD,
445
+ # ABRT and IOT)
446
+ #
447
+ # initial signal handler for aliased signal
448
+ # calls some other signal handler which
449
+ # should not execute the same handler_code again
450
+ if ($called_sig_name eq $signal_name) {
451
+ $handler_code->($signal_name);
452
+ }
453
+
454
+ # run original signal handler if any (including aliased)
455
+ #
456
+ if (ref($previous_handler)) {
457
+ $previous_handler->($called_sig_name, @sig_param);
458
+ }
459
+ };
460
+
461
+ $SIG{$s} = $sig_handler;
462
+ }
463
+
464
+ # give process a chance sending TERM,
465
+ # waiting for a while (2 seconds)
466
+ # and killing it with KILL
467
+ sub kill_gently {
468
+ my ($pid, $opts) = @_;
469
+
470
+ require POSIX;
471
+
472
+ $opts = {} unless $opts;
473
+ $opts->{'wait_time'} = 2 unless defined($opts->{'wait_time'});
474
+ $opts->{'first_kill_type'} = 'just_process' unless $opts->{'first_kill_type'};
475
+ $opts->{'final_kill_type'} = 'just_process' unless $opts->{'final_kill_type'};
476
+
477
+ if ($opts->{'first_kill_type'} eq 'just_process') {
478
+ kill(15, $pid);
479
+ }
480
+ elsif ($opts->{'first_kill_type'} eq 'process_group') {
481
+ kill(-15, $pid);
482
+ }
483
+
484
+ my $do_wait = 1;
485
+ my $child_finished = 0;
486
+
487
+ my $wait_start_time = get_monotonic_time();
488
+ my $now;
489
+ my $previous_monotonic_value;
490
+
491
+ while ($do_wait) {
492
+ $previous_monotonic_value = $now;
493
+ $now = get_monotonic_time();
494
+
495
+ adjust_monotonic_start_time([\$wait_start_time], $now, $previous_monotonic_value);
496
+
497
+ if ($now > $wait_start_time + $opts->{'wait_time'}) {
498
+ $do_wait = 0;
499
+ next;
500
+ }
501
+
502
+ my $waitpid = waitpid($pid, POSIX::WNOHANG);
503
+
504
+ if ($waitpid eq -1) {
505
+ $child_finished = 1;
506
+ $do_wait = 0;
507
+ next;
508
+ }
509
+
510
+ Time::HiRes::usleep(250000); # quarter of a second
511
+ }
512
+
513
+ if (!$child_finished) {
514
+ if ($opts->{'final_kill_type'} eq 'just_process') {
515
+ kill(9, $pid);
516
+ }
517
+ elsif ($opts->{'final_kill_type'} eq 'process_group') {
518
+ kill(-9, $pid);
519
+ }
520
+ }
521
+ }
522
+
523
+ sub open3_run {
524
+ my ($cmd, $opts) = @_;
525
+
526
+ $opts = {} unless $opts;
527
+
528
+ my $child_in = FileHandle->new;
529
+ my $child_out = FileHandle->new;
530
+ my $child_err = FileHandle->new;
531
+ $child_out->autoflush(1);
532
+ $child_err->autoflush(1);
533
+
534
+ my $pid = open3($child_in, $child_out, $child_err, $cmd);
535
+ Time::HiRes::usleep(1) if IS_HPUX;
536
+
537
+ # will consider myself orphan if my ppid changes
538
+ # from this one:
539
+ my $original_ppid = $opts->{'original_ppid'};
540
+
541
+ # push my child's pid to our parent
542
+ # so in case i am killed parent
543
+ # could stop my child (search for
544
+ # child_child_pid in parent code)
545
+ if ($opts->{'parent_info'}) {
546
+ my $ps = $opts->{'parent_info'};
547
+ print $ps "spawned $pid\n";
548
+ }
549
+
550
+ if ($child_in && $child_out->opened && $opts->{'child_stdin'}) {
551
+ # If the child process dies for any reason,
552
+ # the next write to CHLD_IN is likely to generate
553
+ # a SIGPIPE in the parent, which is fatal by default.
554
+ # So you may wish to handle this signal.
555
+ #
556
+ # from http://perldoc.perl.org/IPC/Open3.html,
557
+ # absolutely needed to catch piped commands errors.
558
+ #
559
+ local $SIG{'PIPE'} = sub { 1; };
560
+
561
+ print $child_in $opts->{'child_stdin'};
562
+ }
563
+ close($child_in);
564
+
565
+ my $child_output = {
566
+ 'out' => $child_out->fileno,
567
+ 'err' => $child_err->fileno,
568
+ $child_out->fileno => {
569
+ 'parent_socket' => $opts->{'parent_stdout'},
570
+ 'scalar_buffer' => "",
571
+ 'child_handle' => $child_out,
572
+ 'block_size' => ($child_out->stat)[11] || 1024,
573
+ },
574
+ $child_err->fileno => {
575
+ 'parent_socket' => $opts->{'parent_stderr'},
576
+ 'scalar_buffer' => "",
577
+ 'child_handle' => $child_err,
578
+ 'block_size' => ($child_err->stat)[11] || 1024,
579
+ },
580
+ };
581
+
582
+ my $select = IO::Select->new();
583
+ $select->add($child_out, $child_err);
584
+
585
+ # pass any signal to the child
586
+ # effectively creating process
587
+ # strongly attached to the child:
588
+ # it will terminate only after child
589
+ # has terminated (except for SIGKILL,
590
+ # which is specially handled)
591
+ SIGNAL: foreach my $s (keys %SIG) {
592
+ next SIGNAL if $s eq '__WARN__' or $s eq '__DIE__'; # Skip and don't clobber __DIE__ & __WARN__
593
+ my $sig_handler;
594
+ $sig_handler = sub {
595
+ kill("$s", $pid);
596
+ $SIG{$s} = $sig_handler;
597
+ };
598
+ $SIG{$s} = $sig_handler;
599
+ }
600
+
601
+ my $child_finished = 0;
602
+
603
+ my $real_exit;
604
+ my $exit_value;
605
+
606
+ while(!$child_finished) {
607
+
608
+ # parent was killed otherwise we would have got
609
+ # the same signal as parent and process it same way
610
+ if (getppid() != $original_ppid) {
611
+
612
+ # end my process group with all the children
613
+ # (i am the process group leader, so my pid
614
+ # equals to the process group id)
615
+ #
616
+ # same thing which is done
617
+ # with $opts->{'clean_up_children'}
618
+ # in run_forked
619
+ #
620
+ kill(-9, $$);
621
+
622
+ POSIX::_exit 1;
623
+ }
624
+
625
+ my $waitpid = waitpid($pid, POSIX::WNOHANG);
626
+
627
+ # child finished, catch it's exit status
628
+ if ($waitpid ne 0 && $waitpid ne -1) {
629
+ $real_exit = $?;
630
+ $exit_value = $? >> 8;
631
+ }
632
+
633
+ if ($waitpid eq -1) {
634
+ $child_finished = 1;
635
+ }
636
+
637
+
638
+ my $ready_fds = [];
639
+ push @{$ready_fds}, $select->can_read(1/100);
640
+
641
+ READY_FDS: while (scalar(@{$ready_fds})) {
642
+ my $fd = shift @{$ready_fds};
643
+ $ready_fds = [grep {$_ ne $fd} @{$ready_fds}];
644
+
645
+ my $str = $child_output->{$fd->fileno};
646
+ Carp::confess("child stream not found: $fd") unless $str;
647
+
648
+ my $data;
649
+ my $count = $fd->sysread($data, $str->{'block_size'});
650
+
651
+ if ($count) {
652
+ if ($str->{'parent_socket'}) {
653
+ my $ph = $str->{'parent_socket'};
654
+ print $ph $data;
655
+ }
656
+ else {
657
+ $str->{'scalar_buffer'} .= $data;
658
+ }
659
+ }
660
+ elsif ($count eq 0) {
661
+ $select->remove($fd);
662
+ $fd->close();
663
+ }
664
+ else {
665
+ Carp::confess("error during sysread: " . $!);
666
+ }
667
+
668
+ push @{$ready_fds}, $select->can_read(1/100) if $child_finished;
669
+ }
670
+
671
+ Time::HiRes::usleep(1);
672
+ }
673
+
674
+ # since we've successfully reaped the child,
675
+ # let our parent know about this.
676
+ #
677
+ if ($opts->{'parent_info'}) {
678
+ my $ps = $opts->{'parent_info'};
679
+
680
+ # child was killed, inform parent
681
+ if ($real_exit & 127) {
682
+ print $ps "$pid killed with " . ($real_exit & 127) . "\n";
683
+ }
684
+
685
+ print $ps "reaped $pid\n";
686
+ }
687
+
688
+ if ($opts->{'parent_stdout'} || $opts->{'parent_stderr'}) {
689
+ return $exit_value;
690
+ }
691
+ else {
692
+ return {
693
+ 'stdout' => $child_output->{$child_output->{'out'}}->{'scalar_buffer'},
694
+ 'stderr' => $child_output->{$child_output->{'err'}}->{'scalar_buffer'},
695
+ 'exit_code' => $exit_value,
696
+ };
697
+ }
698
+ }
699
+
700
+ =head2 $hashref = run_forked( COMMAND, { child_stdin => SCALAR, timeout => DIGIT, stdout_handler => CODEREF, stderr_handler => CODEREF} );
701
+
702
+ C<run_forked> is used to execute some program or a coderef,
703
+ optionally feed it with some input, get its return code
704
+ and output (both stdout and stderr into separate buffers).
705
+ In addition, it allows to terminate the program
706
+ if it takes too long to finish.
707
+
708
+ The important and distinguishing feature of run_forked
709
+ is execution timeout which at first seems to be
710
+ quite a simple task but if you think
711
+ that the program which you're spawning
712
+ might spawn some children itself (which
713
+ in their turn could do the same and so on)
714
+ it turns out to be not a simple issue.
715
+
716
+ C<run_forked> is designed to survive and
717
+ successfully terminate almost any long running task,
718
+ even a fork bomb in case your system has the resources
719
+ to survive during given timeout.
720
+
721
+ This is achieved by creating separate watchdog process
722
+ which spawns the specified program in a separate
723
+ process session and supervises it: optionally
724
+ feeds it with input, stores its exit code,
725
+ stdout and stderr, terminates it in case
726
+ it runs longer than specified.
727
+
728
+ Invocation requires the command to be executed or a coderef and optionally a hashref of options:
729
+
730
+ =over
731
+
732
+ =item C<timeout>
733
+
734
+ Specify in seconds how long to run the command before it is killed with SIG_KILL (9),
735
+ which effectively terminates it and all of its children (direct or indirect).
736
+
737
+ =item C<child_stdin>
738
+
739
+ Specify some text that will be passed into the C<STDIN> of the executed program.
740
+
741
+ =item C<stdout_handler>
742
+
743
+ Coderef of a subroutine to call when a portion of data is received on
744
+ STDOUT from the executing program.
745
+
746
+ =item C<stderr_handler>
747
+
748
+ Coderef of a subroutine to call when a portion of data is received on
749
+ STDERR from the executing program.
750
+
751
+ =item C<wait_loop_callback>
752
+
753
+ Coderef of a subroutine to call inside of the main waiting loop
754
+ (while C<run_forked> waits for the external to finish or fail).
755
+ It is useful to stop running external process before it ends
756
+ by itself, e.g.
757
+
758
+ my $r = run_forked("some external command", {
759
+ 'wait_loop_callback' => sub {
760
+ if (condition) {
761
+ kill(1, $$);
762
+ }
763
+ },
764
+ 'terminate_on_signal' => 'HUP',
765
+ });
766
+
767
+ Combined with C<stdout_handler> and C<stderr_handler> allows terminating
768
+ external command based on its output. Could also be used as a timer
769
+ without engaging with L<alarm> (signals).
770
+
771
+ Remember that this code could be called every millisecond (depending
772
+ on the output which external command generates), so try to make it
773
+ as lightweight as possible.
774
+
775
+ =item C<discard_output>
776
+
777
+ Discards the buffering of the standard output and standard errors for return by run_forked().
778
+ With this option you have to use the std*_handlers to read what the command outputs.
779
+ Useful for commands that send a lot of output.
780
+
781
+ =item C<terminate_on_parent_sudden_death>
782
+
783
+ Enable this option if you wish all spawned processes to be killed if the initially spawned
784
+ process (the parent) is killed or dies without waiting for child processes.
785
+
786
+ =back
787
+
788
+ C<run_forked> will return a HASHREF with the following keys:
789
+
790
+ =over
791
+
792
+ =item C<exit_code>
793
+
794
+ The exit code of the executed program.
795
+
796
+ =item C<timeout>
797
+
798
+ The number of seconds the program ran for before being terminated, or 0 if no timeout occurred.
799
+
800
+ =item C<stdout>
801
+
802
+ Holds the standard output of the executed command (or empty string if
803
+ there was no STDOUT output or if C<discard_output> was used; it's always defined!)
804
+
805
+ =item C<stderr>
806
+
807
+ Holds the standard error of the executed command (or empty string if
808
+ there was no STDERR output or if C<discard_output> was used; it's always defined!)
809
+
810
+ =item C<merged>
811
+
812
+ Holds the standard output and error of the executed command merged into one stream
813
+ (or empty string if there was no output at all or if C<discard_output> was used; it's always defined!)
814
+
815
+ =item C<err_msg>
816
+
817
+ Holds some explanation in the case of an error.
818
+
819
+ =back
820
+
821
+ =cut
822
+
823
+ sub run_forked {
824
+ ### container to store things in
825
+ my $self = bless {}, __PACKAGE__;
826
+
827
+ if (!can_use_run_forked()) {
828
+ Carp::carp("run_forked is not available: $CAN_USE_RUN_FORKED");
829
+ return;
830
+ }
831
+
832
+ require POSIX;
833
+
834
+ my ($cmd, $opts) = @_;
835
+ if (ref($cmd) eq 'ARRAY') {
836
+ $cmd = join(" ", @{$cmd});
837
+ }
838
+
839
+ if (!$cmd) {
840
+ Carp::carp("run_forked expects command to run");
841
+ return;
842
+ }
843
+
844
+ $opts = {} unless $opts;
845
+ $opts->{'timeout'} = 0 unless $opts->{'timeout'};
846
+ $opts->{'terminate_wait_time'} = 2 unless defined($opts->{'terminate_wait_time'});
847
+
848
+ # turned on by default
849
+ $opts->{'clean_up_children'} = 1 unless defined($opts->{'clean_up_children'});
850
+
851
+ # sockets to pass child stdout to parent
852
+ my $child_stdout_socket;
853
+ my $parent_stdout_socket;
854
+
855
+ # sockets to pass child stderr to parent
856
+ my $child_stderr_socket;
857
+ my $parent_stderr_socket;
858
+
859
+ # sockets for child -> parent internal communication
860
+ my $child_info_socket;
861
+ my $parent_info_socket;
862
+
863
+ socketpair($child_stdout_socket, $parent_stdout_socket, &Socket::AF_UNIX, &Socket::SOCK_STREAM, &Socket::PF_UNSPEC) ||
864
+ Carp::confess ("socketpair: $!");
865
+ socketpair($child_stderr_socket, $parent_stderr_socket, &Socket::AF_UNIX, &Socket::SOCK_STREAM, &Socket::PF_UNSPEC) ||
866
+ Carp::confess ("socketpair: $!");
867
+ socketpair($child_info_socket, $parent_info_socket, &Socket::AF_UNIX, &Socket::SOCK_STREAM, &Socket::PF_UNSPEC) ||
868
+ Carp::confess ("socketpair: $!");
869
+
870
+ $child_stdout_socket->autoflush(1);
871
+ $parent_stdout_socket->autoflush(1);
872
+ $child_stderr_socket->autoflush(1);
873
+ $parent_stderr_socket->autoflush(1);
874
+ $child_info_socket->autoflush(1);
875
+ $parent_info_socket->autoflush(1);
876
+
877
+ my $start_time = get_monotonic_time();
878
+
879
+ my $pid;
880
+ my $ppid = $$;
881
+ if ($pid = fork) {
882
+
883
+ # we are a parent
884
+ close($parent_stdout_socket);
885
+ close($parent_stderr_socket);
886
+ close($parent_info_socket);
887
+
888
+ my $flags;
889
+
890
+ # prepare sockets to read from child
891
+
892
+ $flags = fcntl($child_stdout_socket, POSIX::F_GETFL, 0) || Carp::confess "can't fnctl F_GETFL: $!";
893
+ $flags |= POSIX::O_NONBLOCK;
894
+ fcntl($child_stdout_socket, POSIX::F_SETFL, $flags) || Carp::confess "can't fnctl F_SETFL: $!";
895
+
896
+ $flags = fcntl($child_stderr_socket, POSIX::F_GETFL, 0) || Carp::confess "can't fnctl F_GETFL: $!";
897
+ $flags |= POSIX::O_NONBLOCK;
898
+ fcntl($child_stderr_socket, POSIX::F_SETFL, $flags) || Carp::confess "can't fnctl F_SETFL: $!";
899
+
900
+ $flags = fcntl($child_info_socket, POSIX::F_GETFL, 0) || Carp::confess "can't fnctl F_GETFL: $!";
901
+ $flags |= POSIX::O_NONBLOCK;
902
+ fcntl($child_info_socket, POSIX::F_SETFL, $flags) || Carp::confess "can't fnctl F_SETFL: $!";
903
+
904
+ # print "child $pid started\n";
905
+
906
+ my $child_output = {
907
+ $child_stdout_socket->fileno => {
908
+ 'scalar_buffer' => "",
909
+ 'child_handle' => $child_stdout_socket,
910
+ 'block_size' => ($child_stdout_socket->stat)[11] || 1024,
911
+ 'protocol' => 'stdout',
912
+ },
913
+ $child_stderr_socket->fileno => {
914
+ 'scalar_buffer' => "",
915
+ 'child_handle' => $child_stderr_socket,
916
+ 'block_size' => ($child_stderr_socket->stat)[11] || 1024,
917
+ 'protocol' => 'stderr',
918
+ },
919
+ $child_info_socket->fileno => {
920
+ 'scalar_buffer' => "",
921
+ 'child_handle' => $child_info_socket,
922
+ 'block_size' => ($child_info_socket->stat)[11] || 1024,
923
+ 'protocol' => 'info',
924
+ },
925
+ };
926
+
927
+ my $select = IO::Select->new();
928
+ $select->add($child_stdout_socket, $child_stderr_socket, $child_info_socket);
929
+
930
+ my $child_timedout = 0;
931
+ my $child_finished = 0;
932
+ my $child_stdout = '';
933
+ my $child_stderr = '';
934
+ my $child_merged = '';
935
+ my $child_exit_code = 0;
936
+ my $child_killed_by_signal = 0;
937
+ my $parent_died = 0;
938
+
939
+ my $last_parent_check = 0;
940
+ my $got_sig_child = 0;
941
+ my $got_sig_quit = 0;
942
+ my $orig_sig_child = $SIG{'CHLD'};
943
+
944
+ $SIG{'CHLD'} = sub { $got_sig_child = get_monotonic_time(); };
945
+
946
+ if ($opts->{'terminate_on_signal'}) {
947
+ install_layered_signal($opts->{'terminate_on_signal'}, sub { $got_sig_quit = time(); });
948
+ }
949
+
950
+ my $child_child_pid;
951
+ my $now;
952
+ my $previous_monotonic_value;
953
+
954
+ while (!$child_finished) {
955
+ $previous_monotonic_value = $now;
956
+ $now = get_monotonic_time();
957
+
958
+ adjust_monotonic_start_time([\$start_time, \$last_parent_check, \$got_sig_child], $now, $previous_monotonic_value);
959
+
960
+ if ($opts->{'terminate_on_parent_sudden_death'}) {
961
+ # check for parent once each five seconds
962
+ if ($now > $last_parent_check + 5) {
963
+ if (getppid() eq "1") {
964
+ kill_gently ($pid, {
965
+ 'first_kill_type' => 'process_group',
966
+ 'final_kill_type' => 'process_group',
967
+ 'wait_time' => $opts->{'terminate_wait_time'}
968
+ });
969
+ $parent_died = 1;
970
+ }
971
+
972
+ $last_parent_check = $now;
973
+ }
974
+ }
975
+
976
+ # user specified timeout
977
+ if ($opts->{'timeout'}) {
978
+ if ($now > $start_time + $opts->{'timeout'}) {
979
+ kill_gently ($pid, {
980
+ 'first_kill_type' => 'process_group',
981
+ 'final_kill_type' => 'process_group',
982
+ 'wait_time' => $opts->{'terminate_wait_time'}
983
+ });
984
+ $child_timedout = 1;
985
+ }
986
+ }
987
+
988
+ # give OS 10 seconds for correct return of waitpid,
989
+ # kill process after that and finish wait loop;
990
+ # shouldn't ever happen -- remove this code?
991
+ if ($got_sig_child) {
992
+ if ($now > $got_sig_child + 10) {
993
+ print STDERR "waitpid did not return -1 for 10 seconds after SIG_CHLD, killing [$pid]\n";
994
+ kill (-9, $pid);
995
+ $child_finished = 1;
996
+ }
997
+ }
998
+
999
+ if ($got_sig_quit) {
1000
+ kill_gently ($pid, {
1001
+ 'first_kill_type' => 'process_group',
1002
+ 'final_kill_type' => 'process_group',
1003
+ 'wait_time' => $opts->{'terminate_wait_time'}
1004
+ });
1005
+ $child_finished = 1;
1006
+ }
1007
+
1008
+ my $waitpid = waitpid($pid, POSIX::WNOHANG);
1009
+
1010
+ # child finished, catch it's exit status
1011
+ if ($waitpid ne 0 && $waitpid ne -1) {
1012
+ $child_exit_code = $? >> 8;
1013
+ }
1014
+
1015
+ if ($waitpid eq -1) {
1016
+ $child_finished = 1;
1017
+ }
1018
+
1019
+ my $ready_fds = [];
1020
+ push @{$ready_fds}, $select->can_read(1/100);
1021
+
1022
+ READY_FDS: while (scalar(@{$ready_fds})) {
1023
+ my $fd = shift @{$ready_fds};
1024
+ $ready_fds = [grep {$_ ne $fd} @{$ready_fds}];
1025
+
1026
+ my $str = $child_output->{$fd->fileno};
1027
+ Carp::confess("child stream not found: $fd") unless $str;
1028
+
1029
+ my $data = "";
1030
+ my $count = $fd->sysread($data, $str->{'block_size'});
1031
+
1032
+ if ($count) {
1033
+ # extract all the available lines and store the rest in temporary buffer
1034
+ if ($data =~ /(.+\n)([^\n]*)/so) {
1035
+ $data = $str->{'scalar_buffer'} . $1;
1036
+ $str->{'scalar_buffer'} = $2 || "";
1037
+ }
1038
+ else {
1039
+ $str->{'scalar_buffer'} .= $data;
1040
+ $data = "";
1041
+ }
1042
+ }
1043
+ elsif ($count eq 0) {
1044
+ $select->remove($fd);
1045
+ $fd->close();
1046
+ if ($str->{'scalar_buffer'}) {
1047
+ $data = $str->{'scalar_buffer'} . "\n";
1048
+ }
1049
+ }
1050
+ else {
1051
+ Carp::confess("error during sysread on [$fd]: " . $!);
1052
+ }
1053
+
1054
+ # $data contains only full lines (or last line if it was unfinished read
1055
+ # or now new-line in the output of the child); dat is processed
1056
+ # according to the "protocol" of socket
1057
+ if ($str->{'protocol'} eq 'info') {
1058
+ if ($data =~ /^spawned ([0-9]+?)\n(.*?)/so) {
1059
+ $child_child_pid = $1;
1060
+ $data = $2;
1061
+ }
1062
+ if ($data =~ /^reaped ([0-9]+?)\n(.*?)/so) {
1063
+ $child_child_pid = undef;
1064
+ $data = $2;
1065
+ }
1066
+ if ($data =~ /^[\d]+ killed with ([0-9]+?)\n(.*?)/so) {
1067
+ $child_killed_by_signal = $1;
1068
+ $data = $2;
1069
+ }
1070
+
1071
+ # we don't expect any other data in info socket, so it's
1072
+ # some strange violation of protocol, better know about this
1073
+ if ($data) {
1074
+ Carp::confess("info protocol violation: [$data]");
1075
+ }
1076
+ }
1077
+ if ($str->{'protocol'} eq 'stdout') {
1078
+ if (!$opts->{'discard_output'}) {
1079
+ $child_stdout .= $data;
1080
+ $child_merged .= $data;
1081
+ }
1082
+
1083
+ if ($opts->{'stdout_handler'} && ref($opts->{'stdout_handler'}) eq 'CODE') {
1084
+ $opts->{'stdout_handler'}->($data);
1085
+ }
1086
+ }
1087
+ if ($str->{'protocol'} eq 'stderr') {
1088
+ if (!$opts->{'discard_output'}) {
1089
+ $child_stderr .= $data;
1090
+ $child_merged .= $data;
1091
+ }
1092
+
1093
+ if ($opts->{'stderr_handler'} && ref($opts->{'stderr_handler'}) eq 'CODE') {
1094
+ $opts->{'stderr_handler'}->($data);
1095
+ }
1096
+ }
1097
+
1098
+ # process may finish (waitpid returns -1) before
1099
+ # we've read all of its output because of buffering;
1100
+ # so try to read all the way it is possible to read
1101
+ # in such case - this shouldn't be too much (unless
1102
+ # the buffer size is HUGE -- should introduce
1103
+ # another counter in such case, maybe later)
1104
+ #
1105
+ push @{$ready_fds}, $select->can_read(1/100) if $child_finished;
1106
+ }
1107
+
1108
+ if ($opts->{'wait_loop_callback'} && ref($opts->{'wait_loop_callback'}) eq 'CODE') {
1109
+ $opts->{'wait_loop_callback'}->();
1110
+ }
1111
+
1112
+ Time::HiRes::usleep(1);
1113
+ }
1114
+
1115
+ # $child_pid_pid is not defined in two cases:
1116
+ # * when our child was killed before
1117
+ # it had chance to tell us the pid
1118
+ # of the child it spawned. we can do
1119
+ # nothing in this case :(
1120
+ # * our child successfully reaped its child,
1121
+ # we have nothing left to do in this case
1122
+ #
1123
+ # defined $child_pid_pid means child's child
1124
+ # has not died but nobody is waiting for it,
1125
+ # killing it brutally.
1126
+ #
1127
+ if ($child_child_pid) {
1128
+ kill_gently($child_child_pid);
1129
+ }
1130
+
1131
+ # in case there are forks in child which
1132
+ # do not forward or process signals (TERM) correctly
1133
+ # kill whole child process group, effectively trying
1134
+ # not to return with some children or their parts still running
1135
+ #
1136
+ # to be more accurate -- we need to be sure
1137
+ # that this is process group created by our child
1138
+ # (and not some other process group with the same pgid,
1139
+ # created just after death of our child) -- fortunately
1140
+ # this might happen only when process group ids
1141
+ # are reused quickly (there are lots of processes
1142
+ # spawning new process groups for example)
1143
+ #
1144
+ if ($opts->{'clean_up_children'}) {
1145
+ kill(-9, $pid);
1146
+ }
1147
+
1148
+ # print "child $pid finished\n";
1149
+
1150
+ close($child_stdout_socket);
1151
+ close($child_stderr_socket);
1152
+ close($child_info_socket);
1153
+
1154
+ my $o = {
1155
+ 'stdout' => $child_stdout,
1156
+ 'stderr' => $child_stderr,
1157
+ 'merged' => $child_merged,
1158
+ 'timeout' => $child_timedout ? $opts->{'timeout'} : 0,
1159
+ 'exit_code' => $child_exit_code,
1160
+ 'parent_died' => $parent_died,
1161
+ 'killed_by_signal' => $child_killed_by_signal,
1162
+ 'child_pgid' => $pid,
1163
+ 'cmd' => $cmd,
1164
+ };
1165
+
1166
+ my $err_msg = '';
1167
+ if ($o->{'exit_code'}) {
1168
+ $err_msg .= "exited with code [$o->{'exit_code'}]\n";
1169
+ }
1170
+ if ($o->{'timeout'}) {
1171
+ $err_msg .= "ran more than [$o->{'timeout'}] seconds\n";
1172
+ }
1173
+ if ($o->{'parent_died'}) {
1174
+ $err_msg .= "parent died\n";
1175
+ }
1176
+ if ($o->{'stdout'} && !$opts->{'non_empty_stdout_ok'}) {
1177
+ $err_msg .= "stdout:\n" . $o->{'stdout'} . "\n";
1178
+ }
1179
+ if ($o->{'stderr'}) {
1180
+ $err_msg .= "stderr:\n" . $o->{'stderr'} . "\n";
1181
+ }
1182
+ if ($o->{'killed_by_signal'}) {
1183
+ $err_msg .= "killed by signal [" . $o->{'killed_by_signal'} . "]\n";
1184
+ }
1185
+ $o->{'err_msg'} = $err_msg;
1186
+
1187
+ if ($orig_sig_child) {
1188
+ $SIG{'CHLD'} = $orig_sig_child;
1189
+ }
1190
+ else {
1191
+ delete($SIG{'CHLD'});
1192
+ }
1193
+
1194
+ uninstall_signals();
1195
+
1196
+ return $o;
1197
+ }
1198
+ else {
1199
+ Carp::confess("cannot fork: $!") unless defined($pid);
1200
+
1201
+ # create new process session for open3 call,
1202
+ # so we hopefully can kill all the subprocesses
1203
+ # which might be spawned in it (except for those
1204
+ # which do setsid theirselves -- can't do anything
1205
+ # with those)
1206
+
1207
+ POSIX::setsid() == -1 and Carp::confess("Error running setsid: " . $!);
1208
+
1209
+ if ($opts->{'child_BEGIN'} && ref($opts->{'child_BEGIN'}) eq 'CODE') {
1210
+ $opts->{'child_BEGIN'}->();
1211
+ }
1212
+
1213
+ close($child_stdout_socket);
1214
+ close($child_stderr_socket);
1215
+ close($child_info_socket);
1216
+
1217
+ my $child_exit_code;
1218
+
1219
+ # allow both external programs
1220
+ # and internal perl calls
1221
+ if (!ref($cmd)) {
1222
+ $child_exit_code = open3_run($cmd, {
1223
+ 'parent_info' => $parent_info_socket,
1224
+ 'parent_stdout' => $parent_stdout_socket,
1225
+ 'parent_stderr' => $parent_stderr_socket,
1226
+ 'child_stdin' => $opts->{'child_stdin'},
1227
+ 'original_ppid' => $ppid,
1228
+ });
1229
+ }
1230
+ elsif (ref($cmd) eq 'CODE') {
1231
+ # reopen STDOUT and STDERR for child code:
1232
+ # https://rt.cpan.org/Ticket/Display.html?id=85912
1233
+ open STDOUT, '>&', $parent_stdout_socket || Carp::confess("Unable to reopen STDOUT: $!\n");
1234
+ open STDERR, '>&', $parent_stderr_socket || Carp::confess("Unable to reopen STDERR: $!\n");
1235
+
1236
+ $child_exit_code = $cmd->({
1237
+ 'opts' => $opts,
1238
+ 'parent_info' => $parent_info_socket,
1239
+ 'parent_stdout' => $parent_stdout_socket,
1240
+ 'parent_stderr' => $parent_stderr_socket,
1241
+ 'child_stdin' => $opts->{'child_stdin'},
1242
+ });
1243
+ }
1244
+ else {
1245
+ print $parent_stderr_socket "Invalid command reference: " . ref($cmd) . "\n";
1246
+ $child_exit_code = 1;
1247
+ }
1248
+
1249
+ close($parent_stdout_socket);
1250
+ close($parent_stderr_socket);
1251
+ close($parent_info_socket);
1252
+
1253
+ if ($opts->{'child_END'} && ref($opts->{'child_END'}) eq 'CODE') {
1254
+ $opts->{'child_END'}->();
1255
+ }
1256
+
1257
+ $| = 1;
1258
+ POSIX::_exit $child_exit_code;
1259
+ }
1260
+ }
1261
+
1262
+ sub run {
1263
+ ### container to store things in
1264
+ my $self = bless {}, __PACKAGE__;
1265
+
1266
+ my %hash = @_;
1267
+
1268
+ ### if the user didn't provide a buffer, we'll store it here.
1269
+ my $def_buf = '';
1270
+
1271
+ my($verbose,$cmd,$buffer,$timeout);
1272
+ my $tmpl = {
1273
+ verbose => { default => $VERBOSE, store => \$verbose },
1274
+ buffer => { default => \$def_buf, store => \$buffer },
1275
+ command => { required => 1, store => \$cmd,
1276
+ allow => sub { !ref($_[0]) or ref($_[0]) eq 'ARRAY' },
1277
+ },
1278
+ timeout => { default => 0, store => \$timeout },
1279
+ };
1280
+
1281
+ unless( check( $tmpl, \%hash, $VERBOSE ) ) {
1282
+ Carp::carp( loc( "Could not validate input: %1",
1283
+ Params::Check->last_error ) );
1284
+ return;
1285
+ };
1286
+
1287
+ $cmd = _quote_args_vms( $cmd ) if IS_VMS;
1288
+
1289
+ ### strip any empty elements from $cmd if present
1290
+ if ( $ALLOW_NULL_ARGS ) {
1291
+ $cmd = [ grep { defined } @$cmd ] if ref $cmd;
1292
+ }
1293
+ else {
1294
+ $cmd = [ grep { defined && length } @$cmd ] if ref $cmd;
1295
+ }
1296
+
1297
+ my $pp_cmd = (ref $cmd ? "@$cmd" : $cmd);
1298
+ print loc("Running [%1]...\n", $pp_cmd ) if $verbose;
1299
+
1300
+ ### did the user pass us a buffer to fill or not? if so, set this
1301
+ ### flag so we know what is expected of us
1302
+ ### XXX this is now being ignored. in the future, we could add diagnostic
1303
+ ### messages based on this logic
1304
+ #my $user_provided_buffer = $buffer == \$def_buf ? 0 : 1;
1305
+
1306
+ ### buffers that are to be captured
1307
+ my( @buffer, @buff_err, @buff_out );
1308
+
1309
+ ### capture STDOUT
1310
+ my $_out_handler = sub {
1311
+ my $buf = shift;
1312
+ return unless defined $buf;
1313
+
1314
+ print STDOUT $buf if $verbose;
1315
+ push @buffer, $buf;
1316
+ push @buff_out, $buf;
1317
+ };
1318
+
1319
+ ### capture STDERR
1320
+ my $_err_handler = sub {
1321
+ my $buf = shift;
1322
+ return unless defined $buf;
1323
+
1324
+ print STDERR $buf if $verbose;
1325
+ push @buffer, $buf;
1326
+ push @buff_err, $buf;
1327
+ };
1328
+
1329
+
1330
+ ### flag to indicate we have a buffer captured
1331
+ my $have_buffer = $self->can_capture_buffer ? 1 : 0;
1332
+
1333
+ ### flag indicating if the subcall went ok
1334
+ my $ok;
1335
+
1336
+ ### don't look at previous errors:
1337
+ local $?;
1338
+ local $@;
1339
+ local $!;
1340
+
1341
+ ### we might be having a timeout set
1342
+ eval {
1343
+ local $SIG{ALRM} = sub { die bless sub {
1344
+ ALARM_CLASS .
1345
+ qq[: Command '$pp_cmd' aborted by alarm after $timeout seconds]
1346
+ }, ALARM_CLASS } if $timeout;
1347
+ alarm $timeout || 0;
1348
+
1349
+ ### IPC::Run is first choice if $USE_IPC_RUN is set.
1350
+ if( !IS_WIN32 and $USE_IPC_RUN and $self->can_use_ipc_run( 1 ) ) {
1351
+ ### ipc::run handlers needs the command as a string or an array ref
1352
+
1353
+ $self->_debug( "# Using IPC::Run. Have buffer: $have_buffer" )
1354
+ if $DEBUG;
1355
+
1356
+ $ok = $self->_ipc_run( $cmd, $_out_handler, $_err_handler );
1357
+
1358
+ ### since IPC::Open3 works on all platforms, and just fails on
1359
+ ### win32 for capturing buffers, do that ideally
1360
+ } elsif ( $USE_IPC_OPEN3 and $self->can_use_ipc_open3( 1 ) ) {
1361
+
1362
+ $self->_debug("# Using IPC::Open3. Have buffer: $have_buffer")
1363
+ if $DEBUG;
1364
+
1365
+ ### in case there are pipes in there;
1366
+ ### IPC::Open3 will call exec and exec will do the right thing
1367
+
1368
+ my $method = IS_WIN32 ? '_open3_run_win32' : '_open3_run';
1369
+
1370
+ $ok = $self->$method(
1371
+ $cmd, $_out_handler, $_err_handler, $verbose
1372
+ );
1373
+
1374
+ ### if we are allowed to run verbose, just dispatch the system command
1375
+ } else {
1376
+ $self->_debug( "# Using system(). Have buffer: $have_buffer" )
1377
+ if $DEBUG;
1378
+ $ok = $self->_system_run( $cmd, $verbose );
1379
+ }
1380
+
1381
+ alarm 0;
1382
+ };
1383
+
1384
+ ### restore STDIN after duping, or STDIN will be closed for
1385
+ ### this current perl process!
1386
+ $self->__reopen_fds( @{ $self->_fds} ) if $self->_fds;
1387
+
1388
+ my $err;
1389
+ unless( $ok ) {
1390
+ ### alarm happened
1391
+ if ( $@ and ref $@ and $@->isa( ALARM_CLASS ) ) {
1392
+ $err = $@->(); # the error code is an expired alarm
1393
+
1394
+ ### another error happened, set by the dispatchub
1395
+ } else {
1396
+ $err = $self->error;
1397
+ }
1398
+ }
1399
+
1400
+ ### fill the buffer;
1401
+ $$buffer = join '', @buffer if @buffer;
1402
+
1403
+ ### return a list of flags and buffers (if available) in list
1404
+ ### context, or just a simple 'ok' in scalar
1405
+ return wantarray
1406
+ ? $have_buffer
1407
+ ? ($ok, $err, \@buffer, \@buff_out, \@buff_err)
1408
+ : ($ok, $err )
1409
+ : $ok
1410
+
1411
+
1412
+ }
1413
+
1414
+ sub _open3_run_win32 {
1415
+ my $self = shift;
1416
+ my $cmd = shift;
1417
+ my $outhand = shift;
1418
+ my $errhand = shift;
1419
+
1420
+ require Socket;
1421
+
1422
+ my $pipe = sub {
1423
+ socketpair($_[0], $_[1], &Socket::AF_UNIX, &Socket::SOCK_STREAM, &Socket::PF_UNSPEC)
1424
+ or return undef;
1425
+ shutdown($_[0], 1); # No more writing for reader
1426
+ shutdown($_[1], 0); # No more reading for writer
1427
+ return 1;
1428
+ };
1429
+
1430
+ my $open3 = sub {
1431
+ local (*TO_CHLD_R, *TO_CHLD_W);
1432
+ local (*FR_CHLD_R, *FR_CHLD_W);
1433
+ local (*FR_CHLD_ERR_R, *FR_CHLD_ERR_W);
1434
+
1435
+ $pipe->(*TO_CHLD_R, *TO_CHLD_W ) or die $^E;
1436
+ $pipe->(*FR_CHLD_R, *FR_CHLD_W ) or die $^E;
1437
+ $pipe->(*FR_CHLD_ERR_R, *FR_CHLD_ERR_W) or die $^E;
1438
+
1439
+ my $pid = IPC::Open3::open3('>&TO_CHLD_R', '<&FR_CHLD_W', '<&FR_CHLD_ERR_W', @_);
1440
+
1441
+ return ( $pid, *TO_CHLD_W, *FR_CHLD_R, *FR_CHLD_ERR_R );
1442
+ };
1443
+
1444
+ $cmd = [ grep { defined && length } @$cmd ] if ref $cmd;
1445
+ $cmd = $self->__fix_cmd_whitespace_and_special_chars( $cmd );
1446
+
1447
+ my ($pid, $to_chld, $fr_chld, $fr_chld_err) =
1448
+ $open3->( ( ref $cmd ? @$cmd : $cmd ) );
1449
+
1450
+ my $in_sel = IO::Select->new();
1451
+ my $out_sel = IO::Select->new();
1452
+
1453
+ my %objs;
1454
+
1455
+ $objs{ fileno( $fr_chld ) } = $outhand;
1456
+ $objs{ fileno( $fr_chld_err ) } = $errhand;
1457
+ $in_sel->add( $fr_chld );
1458
+ $in_sel->add( $fr_chld_err );
1459
+
1460
+ close($to_chld);
1461
+
1462
+ while ($in_sel->count() + $out_sel->count()) {
1463
+ my ($ins, $outs) = IO::Select::select($in_sel, $out_sel, undef);
1464
+
1465
+ for my $fh (@$ins) {
1466
+ my $obj = $objs{ fileno($fh) };
1467
+ my $buf;
1468
+ my $bytes_read = sysread($fh, $buf, 64*1024 ); #, length($buf));
1469
+ if (!$bytes_read) {
1470
+ $in_sel->remove($fh);
1471
+ }
1472
+ else {
1473
+ $obj->( "$buf" );
1474
+ }
1475
+ }
1476
+
1477
+ for my $fh (@$outs) {
1478
+ }
1479
+ }
1480
+
1481
+ waitpid($pid, 0);
1482
+
1483
+ ### some error occurred
1484
+ if( $? ) {
1485
+ $self->error( $self->_pp_child_error( $cmd, $? ) );
1486
+ $self->ok( 0 );
1487
+ return;
1488
+ } else {
1489
+ return $self->ok( 1 );
1490
+ }
1491
+ }
1492
+
1493
+ sub _open3_run {
1494
+ my $self = shift;
1495
+ my $cmd = shift;
1496
+ my $_out_handler = shift;
1497
+ my $_err_handler = shift;
1498
+ my $verbose = shift || 0;
1499
+
1500
+ ### Following code are adapted from Friar 'abstracts' in the
1501
+ ### Perl Monastery (http://www.perlmonks.org/index.pl?node_id=151886).
1502
+ ### XXX that code didn't work.
1503
+ ### we now use the following code, thanks to theorbtwo
1504
+
1505
+ ### define them beforehand, so we always have defined FH's
1506
+ ### to read from.
1507
+ use Symbol;
1508
+ my $kidout = Symbol::gensym();
1509
+ my $kiderror = Symbol::gensym();
1510
+
1511
+ ### Dup the filehandle so we can pass 'our' STDIN to the
1512
+ ### child process. This stops us from having to pump input
1513
+ ### from ourselves to the childprocess. However, we will need
1514
+ ### to revive the FH afterwards, as IPC::Open3 closes it.
1515
+ ### We'll do the same for STDOUT and STDERR. It works without
1516
+ ### duping them on non-unix derivatives, but not on win32.
1517
+ my @fds_to_dup = ( IS_WIN32 && !$verbose
1518
+ ? qw[STDIN STDOUT STDERR]
1519
+ : qw[STDIN]
1520
+ );
1521
+ $self->_fds( \@fds_to_dup );
1522
+ $self->__dup_fds( @fds_to_dup );
1523
+
1524
+ ### pipes have to come in a quoted string, and that clashes with
1525
+ ### whitespace. This sub fixes up such commands so they run properly
1526
+ $cmd = $self->__fix_cmd_whitespace_and_special_chars( $cmd );
1527
+
1528
+ ### don't stringify @$cmd, so spaces in filenames/paths are
1529
+ ### treated properly
1530
+ my $pid = eval {
1531
+ IPC::Open3::open3(
1532
+ '<&STDIN',
1533
+ (IS_WIN32 ? '>&STDOUT' : $kidout),
1534
+ (IS_WIN32 ? '>&STDERR' : $kiderror),
1535
+ ( ref $cmd ? @$cmd : $cmd ),
1536
+ );
1537
+ };
1538
+
1539
+ ### open3 error occurred
1540
+ if( $@ and $@ =~ /^open3:/ ) {
1541
+ $self->ok( 0 );
1542
+ $self->error( $@ );
1543
+ return;
1544
+ };
1545
+
1546
+ ### use OUR stdin, not $kidin. Somehow,
1547
+ ### we never get the input.. so jump through
1548
+ ### some hoops to do it :(
1549
+ my $selector = IO::Select->new(
1550
+ (IS_WIN32 ? \*STDERR : $kiderror),
1551
+ \*STDIN,
1552
+ (IS_WIN32 ? \*STDOUT : $kidout)
1553
+ );
1554
+
1555
+ STDOUT->autoflush(1); STDERR->autoflush(1); STDIN->autoflush(1);
1556
+ $kidout->autoflush(1) if UNIVERSAL::can($kidout, 'autoflush');
1557
+ $kiderror->autoflush(1) if UNIVERSAL::can($kiderror, 'autoflush');
1558
+
1559
+ ### add an explicit break statement
1560
+ ### code courtesy of theorbtwo from #london.pm
1561
+ my $stdout_done = 0;
1562
+ my $stderr_done = 0;
1563
+ OUTER: while ( my @ready = $selector->can_read ) {
1564
+
1565
+ for my $h ( @ready ) {
1566
+ my $buf;
1567
+
1568
+ ### $len is the amount of bytes read
1569
+ my $len = sysread( $h, $buf, 4096 ); # try to read 4096 bytes
1570
+
1571
+ ### see perldoc -f sysread: it returns undef on error,
1572
+ ### so bail out.
1573
+ if( not defined $len ) {
1574
+ warn(loc("Error reading from process: %1", $!));
1575
+ last OUTER;
1576
+ }
1577
+
1578
+ ### check for $len. it may be 0, at which point we're
1579
+ ### done reading, so don't try to process it.
1580
+ ### if we would print anyway, we'd provide bogus information
1581
+ $_out_handler->( "$buf" ) if $len && $h == $kidout;
1582
+ $_err_handler->( "$buf" ) if $len && $h == $kiderror;
1583
+
1584
+ ### Wait till child process is done printing to both
1585
+ ### stdout and stderr.
1586
+ $stdout_done = 1 if $h == $kidout and $len == 0;
1587
+ $stderr_done = 1 if $h == $kiderror and $len == 0;
1588
+ last OUTER if ($stdout_done && $stderr_done);
1589
+ }
1590
+ }
1591
+
1592
+ waitpid $pid, 0; # wait for it to die
1593
+
1594
+ ### restore STDIN after duping, or STDIN will be closed for
1595
+ ### this current perl process!
1596
+ ### done in the parent call now
1597
+ # $self->__reopen_fds( @fds_to_dup );
1598
+
1599
+ ### some error occurred
1600
+ if( $? ) {
1601
+ $self->error( $self->_pp_child_error( $cmd, $? ) );
1602
+ $self->ok( 0 );
1603
+ return;
1604
+ } else {
1605
+ return $self->ok( 1 );
1606
+ }
1607
+ }
1608
+
1609
+ ### Text::ParseWords::shellwords() uses unix semantics. that will break
1610
+ ### on win32
1611
+ { my $parse_sub = IS_WIN32
1612
+ ? __PACKAGE__->can('_split_like_shell_win32')
1613
+ : Text::ParseWords->can('shellwords');
1614
+
1615
+ sub _ipc_run {
1616
+ my $self = shift;
1617
+ my $cmd = shift;
1618
+ my $_out_handler = shift;
1619
+ my $_err_handler = shift;
1620
+
1621
+ STDOUT->autoflush(1); STDERR->autoflush(1);
1622
+
1623
+ ### a command like:
1624
+ # [
1625
+ # '/usr/bin/gzip',
1626
+ # '-cdf',
1627
+ # '/Users/kane/sources/p4/other/archive-extract/t/src/x.tgz',
1628
+ # '|',
1629
+ # '/usr/bin/tar',
1630
+ # '-tf -'
1631
+ # ]
1632
+ ### needs to become:
1633
+ # [
1634
+ # ['/usr/bin/gzip', '-cdf',
1635
+ # '/Users/kane/sources/p4/other/archive-extract/t/src/x.tgz']
1636
+ # '|',
1637
+ # ['/usr/bin/tar', '-tf -']
1638
+ # ]
1639
+
1640
+
1641
+ my @command;
1642
+ my $special_chars;
1643
+
1644
+ my $re = do { my $x = join '', SPECIAL_CHARS; qr/([$x])/ };
1645
+ if( ref $cmd ) {
1646
+ my $aref = [];
1647
+ for my $item (@$cmd) {
1648
+ if( $item =~ $re ) {
1649
+ push @command, $aref, $item;
1650
+ $aref = [];
1651
+ $special_chars .= $1;
1652
+ } else {
1653
+ push @$aref, $item;
1654
+ }
1655
+ }
1656
+ push @command, $aref;
1657
+ } else {
1658
+ @command = map { if( $_ =~ $re ) {
1659
+ $special_chars .= $1; $_;
1660
+ } else {
1661
+ # [ split /\s+/ ]
1662
+ [ map { m/[ ]/ ? qq{'$_'} : $_ } $parse_sub->($_) ]
1663
+ }
1664
+ } split( /\s*$re\s*/, $cmd );
1665
+ }
1666
+
1667
+ ### if there's a pipe in the command, *STDIN needs to
1668
+ ### be inserted *BEFORE* the pipe, to work on win32
1669
+ ### this also works on *nix, so we should do it when possible
1670
+ ### this should *also* work on multiple pipes in the command
1671
+ ### if there's no pipe in the command, append STDIN to the back
1672
+ ### of the command instead.
1673
+ ### XXX seems IPC::Run works it out for itself if you just
1674
+ ### don't pass STDIN at all.
1675
+ # if( $special_chars and $special_chars =~ /\|/ ) {
1676
+ # ### only add STDIN the first time..
1677
+ # my $i;
1678
+ # @command = map { ($_ eq '|' && not $i++)
1679
+ # ? ( \*STDIN, $_ )
1680
+ # : $_
1681
+ # } @command;
1682
+ # } else {
1683
+ # push @command, \*STDIN;
1684
+ # }
1685
+
1686
+ # \*STDIN is already included in the @command, see a few lines up
1687
+ my $ok = eval { IPC::Run::run( @command,
1688
+ fileno(STDOUT).'>',
1689
+ $_out_handler,
1690
+ fileno(STDERR).'>',
1691
+ $_err_handler
1692
+ )
1693
+ };
1694
+
1695
+ ### all is well
1696
+ if( $ok ) {
1697
+ return $self->ok( $ok );
1698
+
1699
+ ### some error occurred
1700
+ } else {
1701
+ $self->ok( 0 );
1702
+
1703
+ ### if the eval fails due to an exception, deal with it
1704
+ ### unless it's an alarm
1705
+ if( $@ and not UNIVERSAL::isa( $@, ALARM_CLASS ) ) {
1706
+ $self->error( $@ );
1707
+
1708
+ ### if it *is* an alarm, propagate
1709
+ } elsif( $@ ) {
1710
+ die $@;
1711
+
1712
+ ### some error in the sub command
1713
+ } else {
1714
+ $self->error( $self->_pp_child_error( $cmd, $? ) );
1715
+ }
1716
+
1717
+ return;
1718
+ }
1719
+ }
1720
+ }
1721
+
1722
+ sub _system_run {
1723
+ my $self = shift;
1724
+ my $cmd = shift;
1725
+ my $verbose = shift || 0;
1726
+
1727
+ ### pipes have to come in a quoted string, and that clashes with
1728
+ ### whitespace. This sub fixes up such commands so they run properly
1729
+ $cmd = $self->__fix_cmd_whitespace_and_special_chars( $cmd );
1730
+
1731
+ my @fds_to_dup = $verbose ? () : qw[STDOUT STDERR];
1732
+ $self->_fds( \@fds_to_dup );
1733
+ $self->__dup_fds( @fds_to_dup );
1734
+
1735
+ ### system returns 'true' on failure -- the exit code of the cmd
1736
+ $self->ok( 1 );
1737
+ system( ref $cmd ? @$cmd : $cmd ) == 0 or do {
1738
+ $self->error( $self->_pp_child_error( $cmd, $? ) );
1739
+ $self->ok( 0 );
1740
+ };
1741
+
1742
+ ### done in the parent call now
1743
+ #$self->__reopen_fds( @fds_to_dup );
1744
+
1745
+ return unless $self->ok;
1746
+ return $self->ok;
1747
+ }
1748
+
1749
+ { my %sc_lookup = map { $_ => $_ } SPECIAL_CHARS;
1750
+
1751
+
1752
+ sub __fix_cmd_whitespace_and_special_chars {
1753
+ my $self = shift;
1754
+ my $cmd = shift;
1755
+
1756
+ ### command has a special char in it
1757
+ if( ref $cmd and grep { $sc_lookup{$_} } @$cmd ) {
1758
+
1759
+ ### since we have special chars, we have to quote white space
1760
+ ### this *may* conflict with the parsing :(
1761
+ my $fixed;
1762
+ my @cmd = map { / / ? do { $fixed++; QUOTE.$_.QUOTE } : $_ } @$cmd;
1763
+
1764
+ $self->_debug( "# Quoted $fixed arguments containing whitespace" )
1765
+ if $DEBUG && $fixed;
1766
+
1767
+ ### stringify it, so the special char isn't escaped as argument
1768
+ ### to the program
1769
+ $cmd = join ' ', @cmd;
1770
+ }
1771
+
1772
+ return $cmd;
1773
+ }
1774
+ }
1775
+
1776
+ ### Command-line arguments (but not the command itself) must be quoted
1777
+ ### to ensure case preservation. Borrowed from Module::Build with adaptations.
1778
+ ### Patch for this supplied by Craig Berry, see RT #46288: [PATCH] Add argument
1779
+ ### quoting for run() on VMS
1780
+ sub _quote_args_vms {
1781
+ ### Returns a command string with proper quoting so that the subprocess
1782
+ ### sees this same list of args, or if we get a single arg that is an
1783
+ ### array reference, quote the elements of it (except for the first)
1784
+ ### and return the reference.
1785
+ my @args = @_;
1786
+ my $got_arrayref = (scalar(@args) == 1
1787
+ && UNIVERSAL::isa($args[0], 'ARRAY'))
1788
+ ? 1
1789
+ : 0;
1790
+
1791
+ @args = split(/\s+/, $args[0]) unless $got_arrayref || scalar(@args) > 1;
1792
+
1793
+ my $cmd = $got_arrayref ? shift @{$args[0]} : shift @args;
1794
+
1795
+ ### Do not quote qualifiers that begin with '/' or previously quoted args.
1796
+ map { if (/^[^\/\"]/) {
1797
+ $_ =~ s/\"/""/g; # escape C<"> by doubling
1798
+ $_ = q(").$_.q(");
1799
+ }
1800
+ }
1801
+ ($got_arrayref ? @{$args[0]}
1802
+ : @args
1803
+ );
1804
+
1805
+ $got_arrayref ? unshift(@{$args[0]}, $cmd) : unshift(@args, $cmd);
1806
+
1807
+ return $got_arrayref ? $args[0]
1808
+ : join(' ', @args);
1809
+ }
1810
+
1811
+
1812
+ ### XXX this is cribbed STRAIGHT from M::B 0.30 here:
1813
+ ### http://search.cpan.org/src/KWILLIAMS/Module-Build-0.30/lib/Module/Build/Platform/Windows.pm:split_like_shell
1814
+ ### XXX this *should* be integrated into text::parsewords
1815
+ sub _split_like_shell_win32 {
1816
+ # As it turns out, Windows command-parsing is very different from
1817
+ # Unix command-parsing. Double-quotes mean different things,
1818
+ # backslashes don't necessarily mean escapes, and so on. So we
1819
+ # can't use Text::ParseWords::shellwords() to break a command string
1820
+ # into words. The algorithm below was bashed out by Randy and Ken
1821
+ # (mostly Randy), and there are a lot of regression tests, so we
1822
+ # should feel free to adjust if desired.
1823
+
1824
+ local $_ = shift;
1825
+
1826
+ my @argv;
1827
+ return @argv unless defined() && length();
1828
+
1829
+ my $arg = '';
1830
+ my( $i, $quote_mode ) = ( 0, 0 );
1831
+
1832
+ while ( $i < length() ) {
1833
+
1834
+ my $ch = substr( $_, $i , 1 );
1835
+ my $next_ch = substr( $_, $i+1, 1 );
1836
+
1837
+ if ( $ch eq '\\' && $next_ch eq '"' ) {
1838
+ $arg .= '"';
1839
+ $i++;
1840
+ } elsif ( $ch eq '\\' && $next_ch eq '\\' ) {
1841
+ $arg .= '\\';
1842
+ $i++;
1843
+ } elsif ( $ch eq '"' && $next_ch eq '"' && $quote_mode ) {
1844
+ $quote_mode = !$quote_mode;
1845
+ $arg .= '"';
1846
+ $i++;
1847
+ } elsif ( $ch eq '"' && $next_ch eq '"' && !$quote_mode &&
1848
+ ( $i + 2 == length() ||
1849
+ substr( $_, $i + 2, 1 ) eq ' ' )
1850
+ ) { # for cases like: a"" => [ 'a' ]
1851
+ push( @argv, $arg );
1852
+ $arg = '';
1853
+ $i += 2;
1854
+ } elsif ( $ch eq '"' ) {
1855
+ $quote_mode = !$quote_mode;
1856
+ } elsif ( $ch eq ' ' && !$quote_mode ) {
1857
+ push( @argv, $arg ) if defined( $arg ) && length( $arg );
1858
+ $arg = '';
1859
+ ++$i while substr( $_, $i + 1, 1 ) eq ' ';
1860
+ } else {
1861
+ $arg .= $ch;
1862
+ }
1863
+
1864
+ $i++;
1865
+ }
1866
+
1867
+ push( @argv, $arg ) if defined( $arg ) && length( $arg );
1868
+ return @argv;
1869
+ }
1870
+
1871
+
1872
+
1873
+ { use File::Spec;
1874
+ use Symbol;
1875
+
1876
+ my %Map = (
1877
+ STDOUT => [qw|>&|, \*STDOUT, Symbol::gensym() ],
1878
+ STDERR => [qw|>&|, \*STDERR, Symbol::gensym() ],
1879
+ STDIN => [qw|<&|, \*STDIN, Symbol::gensym() ],
1880
+ );
1881
+
1882
+ ### dups FDs and stores them in a cache
1883
+ sub __dup_fds {
1884
+ my $self = shift;
1885
+ my @fds = @_;
1886
+
1887
+ __PACKAGE__->_debug( "# Closing the following fds: @fds" ) if $DEBUG;
1888
+
1889
+ for my $name ( @fds ) {
1890
+ my($redir, $fh, $glob) = @{$Map{$name}} or (
1891
+ Carp::carp(loc("No such FD: '%1'", $name)), next );
1892
+
1893
+ ### MUST use the 2-arg version of open for dup'ing for
1894
+ ### 5.6.x compatibility. 5.8.x can use 3-arg open
1895
+ ### see perldoc5.6.2 -f open for details
1896
+ open $glob, $redir . fileno($fh) or (
1897
+ Carp::carp(loc("Could not dup '$name': %1", $!)),
1898
+ return
1899
+ );
1900
+
1901
+ ### we should re-open this filehandle right now, not
1902
+ ### just dup it
1903
+ ### Use 2-arg version of open, as 5.5.x doesn't support
1904
+ ### 3-arg version =/
1905
+ if( $redir eq '>&' ) {
1906
+ open( $fh, '>' . File::Spec->devnull ) or (
1907
+ Carp::carp(loc("Could not reopen '$name': %1", $!)),
1908
+ return
1909
+ );
1910
+ }
1911
+ }
1912
+
1913
+ return 1;
1914
+ }
1915
+
1916
+ ### reopens FDs from the cache
1917
+ sub __reopen_fds {
1918
+ my $self = shift;
1919
+ my @fds = @_;
1920
+
1921
+ __PACKAGE__->_debug( "# Reopening the following fds: @fds" ) if $DEBUG;
1922
+
1923
+ for my $name ( @fds ) {
1924
+ my($redir, $fh, $glob) = @{$Map{$name}} or (
1925
+ Carp::carp(loc("No such FD: '%1'", $name)), next );
1926
+
1927
+ ### MUST use the 2-arg version of open for dup'ing for
1928
+ ### 5.6.x compatibility. 5.8.x can use 3-arg open
1929
+ ### see perldoc5.6.2 -f open for details
1930
+ open( $fh, $redir . fileno($glob) ) or (
1931
+ Carp::carp(loc("Could not restore '$name': %1", $!)),
1932
+ return
1933
+ );
1934
+
1935
+ ### close this FD, we're not using it anymore
1936
+ close $glob;
1937
+ }
1938
+ return 1;
1939
+
1940
+ }
1941
+ }
1942
+
1943
+ sub _debug {
1944
+ my $self = shift;
1945
+ my $msg = shift or return;
1946
+ my $level = shift || 0;
1947
+
1948
+ local $Carp::CarpLevel += $level;
1949
+ Carp::carp($msg);
1950
+
1951
+ return 1;
1952
+ }
1953
+
1954
+ sub _pp_child_error {
1955
+ my $self = shift;
1956
+ my $cmd = shift or return;
1957
+ my $ce = shift or return;
1958
+ my $pp_cmd = ref $cmd ? "@$cmd" : $cmd;
1959
+
1960
+
1961
+ my $str;
1962
+ if( $ce == -1 ) {
1963
+ ### Include $! in the error message, so that the user can
1964
+ ### see 'No such file or directory' versus 'Permission denied'
1965
+ ### versus 'Cannot fork' or whatever the cause was.
1966
+ $str = "Failed to execute '$pp_cmd': $!";
1967
+
1968
+ } elsif ( $ce & 127 ) {
1969
+ ### some signal
1970
+ $str = loc( "'%1' died with signal %2, %3 coredump",
1971
+ $pp_cmd, ($ce & 127), ($ce & 128) ? 'with' : 'without');
1972
+
1973
+ } else {
1974
+ ### Otherwise, the command run but gave error status.
1975
+ $str = "'$pp_cmd' exited with value " . ($ce >> 8);
1976
+ }
1977
+
1978
+ $self->_debug( "# Child error '$ce' translated to: $str" ) if $DEBUG;
1979
+
1980
+ return $str;
1981
+ }
1982
+
1983
+ 1;
1984
+
1985
+ __END__
1986
+
1987
+ =head2 $q = QUOTE
1988
+
1989
+ Returns the character used for quoting strings on this platform. This is
1990
+ usually a C<'> (single quote) on most systems, but some systems use different
1991
+ quotes. For example, C<Win32> uses C<"> (double quote).
1992
+
1993
+ You can use it as follows:
1994
+
1995
+ use IPC::Cmd qw[run QUOTE];
1996
+ my $cmd = q[echo ] . QUOTE . q[foo bar] . QUOTE;
1997
+
1998
+ This makes sure that C<foo bar> is treated as a string, rather than two
1999
+ separate arguments to the C<echo> function.
2000
+
2001
+ =head1 HOW IT WORKS
2002
+
2003
+ C<run> will try to execute your command using the following logic:
2004
+
2005
+ =over 4
2006
+
2007
+ =item *
2008
+
2009
+ If you have C<IPC::Run> installed, and the variable C<$IPC::Cmd::USE_IPC_RUN>
2010
+ is set to true (See the L<"Global Variables"> section) use that to execute
2011
+ the command. You will have the full output available in buffers, interactive commands
2012
+ are sure to work and you are guaranteed to have your verbosity
2013
+ settings honored cleanly.
2014
+
2015
+ =item *
2016
+
2017
+ Otherwise, if the variable C<$IPC::Cmd::USE_IPC_OPEN3> is set to true
2018
+ (See the L<"Global Variables"> section), try to execute the command using
2019
+ L<IPC::Open3>. Buffers will be available on all platforms,
2020
+ interactive commands will still execute cleanly, and also your verbosity
2021
+ settings will be adhered to nicely;
2022
+
2023
+ =item *
2024
+
2025
+ Otherwise, if you have the C<verbose> argument set to true, we fall back
2026
+ to a simple C<system()> call. We cannot capture any buffers, but
2027
+ interactive commands will still work.
2028
+
2029
+ =item *
2030
+
2031
+ Otherwise we will try and temporarily redirect STDERR and STDOUT, do a
2032
+ C<system()> call with your command and then re-open STDERR and STDOUT.
2033
+ This is the method of last resort and will still allow you to execute
2034
+ your commands cleanly. However, no buffers will be available.
2035
+
2036
+ =back
2037
+
2038
+ =head1 Global Variables
2039
+
2040
+ The behaviour of IPC::Cmd can be altered by changing the following
2041
+ global variables:
2042
+
2043
+ =head2 $IPC::Cmd::VERBOSE
2044
+
2045
+ This controls whether IPC::Cmd will print any output from the
2046
+ commands to the screen or not. The default is 0.
2047
+
2048
+ =head2 $IPC::Cmd::USE_IPC_RUN
2049
+
2050
+ This variable controls whether IPC::Cmd will try to use L<IPC::Run>
2051
+ when available and suitable.
2052
+
2053
+ =head2 $IPC::Cmd::USE_IPC_OPEN3
2054
+
2055
+ This variable controls whether IPC::Cmd will try to use L<IPC::Open3>
2056
+ when available and suitable. Defaults to true.
2057
+
2058
+ =head2 $IPC::Cmd::WARN
2059
+
2060
+ This variable controls whether run-time warnings should be issued, like
2061
+ the failure to load an C<IPC::*> module you explicitly requested.
2062
+
2063
+ Defaults to true. Turn this off at your own risk.
2064
+
2065
+ =head2 $IPC::Cmd::INSTANCES
2066
+
2067
+ This variable controls whether C<can_run> will return all instances of
2068
+ the binary it finds in the C<PATH> when called in a list context.
2069
+
2070
+ Defaults to false, set to true to enable the described behaviour.
2071
+
2072
+ =head2 $IPC::Cmd::ALLOW_NULL_ARGS
2073
+
2074
+ This variable controls whether C<run> will remove any empty/null arguments
2075
+ it finds in command arguments.
2076
+
2077
+ Defaults to false, so it will remove null arguments. Set to true to allow
2078
+ them.
2079
+
2080
+ =head1 Caveats
2081
+
2082
+ =over 4
2083
+
2084
+ =item Whitespace and IPC::Open3 / system()
2085
+
2086
+ When using C<IPC::Open3> or C<system>, if you provide a string as the
2087
+ C<command> argument, it is assumed to be appropriately escaped. You can
2088
+ use the C<QUOTE> constant to use as a portable quote character (see above).
2089
+ However, if you provide an array reference, special rules apply:
2090
+
2091
+ If your command contains B<special characters> (< > | &), it will
2092
+ be internally stringified before executing the command, to avoid that these
2093
+ special characters are escaped and passed as arguments instead of retaining
2094
+ their special meaning.
2095
+
2096
+ However, if the command contained arguments that contained whitespace,
2097
+ stringifying the command would lose the significance of the whitespace.
2098
+ Therefore, C<IPC::Cmd> will quote any arguments containing whitespace in your
2099
+ command if the command is passed as an arrayref and contains special characters.
2100
+
2101
+ =item Whitespace and IPC::Run
2102
+
2103
+ When using C<IPC::Run>, if you provide a string as the C<command> argument,
2104
+ the string will be split on whitespace to determine the individual elements
2105
+ of your command. Although this will usually just Do What You Mean, it may
2106
+ break if you have files or commands with whitespace in them.
2107
+
2108
+ If you do not wish this to happen, you should provide an array
2109
+ reference, where all parts of your command are already separated out.
2110
+ Note however, if there are extra or spurious whitespaces in these parts,
2111
+ the parser or underlying code may not interpret it correctly, and
2112
+ cause an error.
2113
+
2114
+ Example:
2115
+ The following code
2116
+
2117
+ gzip -cdf foo.tar.gz | tar -xf -
2118
+
2119
+ should either be passed as
2120
+
2121
+ "gzip -cdf foo.tar.gz | tar -xf -"
2122
+
2123
+ or as
2124
+
2125
+ ['gzip', '-cdf', 'foo.tar.gz', '|', 'tar', '-xf', '-']
2126
+
2127
+ But take care not to pass it as, for example
2128
+
2129
+ ['gzip -cdf foo.tar.gz', '|', 'tar -xf -']
2130
+
2131
+ Since this will lead to issues as described above.
2132
+
2133
+
2134
+ =item IO Redirect
2135
+
2136
+ Currently it is too complicated to parse your command for IO
2137
+ redirections. For capturing STDOUT or STDERR there is a work around
2138
+ however, since you can just inspect your buffers for the contents.
2139
+
2140
+ =item Interleaving STDOUT/STDERR
2141
+
2142
+ Neither IPC::Run nor IPC::Open3 can interleave STDOUT and STDERR. For short
2143
+ bursts of output from a program, e.g. this sample,
2144
+
2145
+ for ( 1..4 ) {
2146
+ $_ % 2 ? print STDOUT $_ : print STDERR $_;
2147
+ }
2148
+
2149
+ IPC::[Run|Open3] will first read all of STDOUT, then all of STDERR, meaning
2150
+ the output looks like '13' on STDOUT and '24' on STDERR, instead of
2151
+
2152
+ 1
2153
+ 2
2154
+ 3
2155
+ 4
2156
+
2157
+ This has been recorded in L<rt.cpan.org> as bug #37532: Unable to interleave
2158
+ STDOUT and STDERR.
2159
+
2160
+ =back
2161
+
2162
+ =head1 See Also
2163
+
2164
+ L<IPC::Run>, L<IPC::Open3>
2165
+
2166
+ =head1 ACKNOWLEDGEMENTS
2167
+
2168
+ Thanks to James Mastros and Martijn van der Streek for their
2169
+ help in getting L<IPC::Open3> to behave nicely.
2170
+
2171
+ Thanks to Petya Kohts for the C<run_forked> code.
2172
+
2173
+ =head1 BUG REPORTS
2174
+
2175
+ Please report bugs or other issues to E<lt>bug-ipc-cmd@rt.cpan.orgE<gt>.
2176
+
2177
+ =head1 AUTHOR
2178
+
2179
+ Original author: Jos Boumans E<lt>kane@cpan.orgE<gt>.
2180
+ Current maintainer: Chris Williams E<lt>bingos@cpan.orgE<gt>.
2181
+
2182
+ =head1 COPYRIGHT
2183
+
2184
+ This library is free software; you may redistribute and/or modify it
2185
+ under the same terms as Perl itself.
2186
+
2187
+ =cut
git/usr/share/perl5/core_perl/IPC/Open2.pm ADDED
@@ -0,0 +1,173 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package IPC::Open2;
2
+
3
+ use strict;
4
+
5
+ require 5.006;
6
+ use Exporter 'import';
7
+
8
+ our $VERSION = 1.08;
9
+ our @EXPORT = qw(open2);
10
+
11
+ =head1 NAME
12
+
13
+ IPC::Open2 - open a process for both reading and writing using open2()
14
+
15
+ =head1 SYNOPSIS
16
+
17
+ use IPC::Open2;
18
+
19
+ my $pid = open2(my $chld_out, my $chld_in,
20
+ 'some', 'cmd', 'and', 'args');
21
+ # or passing the command through the shell
22
+ my $pid = open2(my $chld_out, my $chld_in, 'some cmd and args');
23
+
24
+ # read from parent STDIN and write to already open handle
25
+ open my $outfile, '>', 'outfile.txt' or die "open failed: $!";
26
+ my $pid = open2(['&', $outfile], ['&', *STDIN],
27
+ 'some', 'cmd', 'and', 'args');
28
+
29
+ # read from already open handle and write to parent STDOUT
30
+ open my $infile, '<', 'infile.txt' or die "open failed: $!";
31
+ my $pid = open2(['&', *STDOUT], ['&', $infile],
32
+ 'some', 'cmd', 'and', 'args');
33
+
34
+ # reap zombie and retrieve exit status
35
+ waitpid( $pid, 0 );
36
+ my $child_exit_status = $? >> 8;
37
+
38
+ =head1 DESCRIPTION
39
+
40
+ The C<open2()> function runs the given command and connects C<$chld_out> for
41
+ reading and C<$chld_in> for writing. It's what you think should work
42
+ when you try
43
+
44
+ my $pid = open(my $fh, "|cmd args|"); # ERROR
45
+
46
+ but you have to write it as:
47
+
48
+ my $pid = open2($chld_out, $chld_in, @command_and_args);
49
+
50
+ The C<$chld_in> filehandle will have autoflush turned on.
51
+
52
+ By default, the filehandles you pass in are used as output parameters.
53
+ C<open2> internally creates two pipes. The write end of the first pipe and the
54
+ read end of the second pipe are connected to the command's standard output and
55
+ input, respectively. The corresponding read and write ends are placed in the
56
+ first and second argument to C<open2>.
57
+
58
+ The filehandle arguments can take the following forms:
59
+
60
+ =over
61
+
62
+ =item *
63
+
64
+ An uninitialized variable (technically, either C<undef> or the empty string
65
+ will work): C<open2> generates a fresh filehandle and assigns it to the
66
+ argument, which must be a modifiable variable for this work (otherwise an
67
+ exception will be raised).
68
+
69
+ =item *
70
+
71
+ An existing handle in the form of a typeglob like C<*STDIN> or C<*FOO> or a
72
+ reference to such: C<open2> places the filehandle in the C<IO> slot of the
73
+ typeglob, which means the corresponding bareword filehandle (like C<STDIN> or
74
+ C<FOO>) can be used for I/O from/to the child process. (If the handle is
75
+ already open, it is automatically closed first.)
76
+
77
+ =item *
78
+
79
+ A string containing the name of a bareword handle (like C<'STDIN'> or
80
+ C<'FOO'>): Such strings are resolved to typeglobs at runtime and then act like
81
+ the case described above.
82
+
83
+ =back
84
+
85
+ However, it is possible to make C<open2> use an existing handle directly (as an
86
+ input argument) and skip the creation of a pipe. To do this, the filehandle
87
+ argument must have one of the following two forms:
88
+
89
+ =over
90
+
91
+ =item *
92
+
93
+ An array reference like C<['&', $fh]>, i.e. the first element is the string
94
+ C<'&'> and the second element is the existing handle to use in the child
95
+ process.
96
+
97
+ =item *
98
+
99
+ A string of the form C<< '<&FOO' >> or C<< '>&FOO' >>, i.e. a string starting
100
+ with the two characters C<< <& >> (for input) or C<< >& >> (for output),
101
+ followed by the name of a bareword filehandle. (The string form cannot be used
102
+ with handles stored in variables.)
103
+
104
+ =back
105
+
106
+ If you use this form for C<$chld_in>, the filehandle will be closed in the
107
+ parent process.
108
+
109
+ C<open2> returns the process ID of the child process. It doesn't return on
110
+ failure: it just raises an exception matching C</^open2:/>. However,
111
+ C<exec> failures in the child are not detected. You'll have to
112
+ trap SIGPIPE yourself.
113
+
114
+ C<open2> does not wait for and reap the child process after it exits.
115
+ Except for short programs where it's acceptable to let the operating system
116
+ take care of this, you need to do this yourself. This is normally as
117
+ simple as calling C<waitpid $pid, 0> when you're done with the process.
118
+ Failing to do this can result in an accumulation of defunct or "zombie"
119
+ processes. See L<perlfunc/waitpid> for more information.
120
+
121
+ This whole affair is quite dangerous, as you may block forever. It
122
+ assumes it's going to talk to something like L<bc(1)>, both writing
123
+ to it and reading from it. This is presumably safe because you
124
+ "know" that commands like L<bc(1)> will read a line at a time and
125
+ output a line at a time. Programs like L<sort(1)> that read their
126
+ entire input stream first, however, are quite apt to cause deadlock.
127
+
128
+ The big problem with this approach is that if you don't have control
129
+ over source code being run in the child process, you can't control
130
+ what it does with pipe buffering. Thus you can't just open a pipe to
131
+ C<cat -v> and continually read and write a line from it.
132
+
133
+ The L<IO::Pty> and L<Expect> modules from CPAN can help with this, as
134
+ they provide a real tty (well, a pseudo-tty, actually), which gets you
135
+ back to line buffering in the invoked command again.
136
+
137
+ =head1 WARNING
138
+
139
+ The order of arguments differs from that of C<open3> from L<IPC::Open3>.
140
+
141
+ =head1 SEE ALSO
142
+
143
+ See L<IPC::Open3> for an alternative that handles C<STDERR> as well. This
144
+ function is really just a wrapper around C<open3>.
145
+
146
+ =cut
147
+
148
+ # &open2: tom christiansen, <tchrist@convex.com>
149
+ #
150
+ # usage: $pid = open2('rdr', 'wtr', 'some cmd and args');
151
+ # or $pid = open2('rdr', 'wtr', 'some', 'cmd', 'and', 'args');
152
+ #
153
+ # spawn the given $cmd and connect $rdr for
154
+ # reading and $wtr for writing. return pid
155
+ # of child, or 0 on failure.
156
+ #
157
+ # WARNING: this is dangerous, as you may block forever
158
+ # unless you are very careful.
159
+ #
160
+ # $wtr is left unbuffered.
161
+ #
162
+ # abort program if
163
+ # rdr or wtr are null
164
+ # a system call fails
165
+
166
+ require IPC::Open3;
167
+
168
+ sub open2 {
169
+ local $Carp::CarpLevel = $Carp::CarpLevel + 1;
170
+ return IPC::Open3::_open3('open2', $_[1], $_[0], '>&STDERR', @_[2 .. $#_]);
171
+ }
172
+
173
+ 1
git/usr/share/perl5/core_perl/IPC/Open3.pm ADDED
@@ -0,0 +1,507 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package IPC::Open3;
2
+
3
+ use strict;
4
+ no strict 'refs'; # because users pass me bareword filehandles
5
+
6
+ use Exporter 'import';
7
+
8
+ use Carp;
9
+ use Symbol qw(gensym qualify);
10
+
11
+ our $VERSION = '1.24';
12
+ our @EXPORT = qw(open3);
13
+
14
+ =head1 NAME
15
+
16
+ IPC::Open3 - open a process for reading, writing, and error handling using open3()
17
+
18
+ =head1 SYNOPSIS
19
+
20
+ use Symbol 'gensym'; # vivify a separate handle for STDERR
21
+ my $pid = open3(my $chld_in, my $chld_out, my $chld_err = gensym,
22
+ 'some', 'cmd', 'and', 'args');
23
+ # or pass the command through the shell
24
+ my $pid = open3(my $chld_in, my $chld_out, my $chld_err = gensym,
25
+ 'some cmd and args');
26
+
27
+ # read from parent STDIN
28
+ # send STDOUT and STDERR to already open handle
29
+ open my $outfile, '>>', 'output.txt' or die "open failed: $!";
30
+ my $pid = open3(['&', *STDIN], ['&', $outfile], undef,
31
+ 'some', 'cmd', 'and', 'args');
32
+
33
+ # write to parent STDOUT and STDERR
34
+ my $pid = open3(my $chld_in, ['&', *STDOUT], ['&', *STDERR],
35
+ 'some', 'cmd', 'and', 'args');
36
+
37
+ # reap zombie and retrieve exit status
38
+ waitpid( $pid, 0 );
39
+ my $child_exit_status = $? >> 8;
40
+
41
+ =head1 DESCRIPTION
42
+
43
+ Extremely similar to C<open2> from L<IPC::Open2>, C<open3> spawns the given
44
+ command and provides filehandles for interacting with the command's standard
45
+ I/O streams.
46
+
47
+ my $pid = open3($chld_in, $chld_out, $chld_err, @command_and_args);
48
+
49
+ It connects C<$chld_in> for writing to the child's standard input, C<$chld_out>
50
+ for reading from the child's standard output, and C<$chld_err> for reading from
51
+ the child's standard error stream. If C<$chld_err> is false, or the same file
52
+ descriptor as C<$chld_out>, then C<STDOUT> and C<STDERR> of the child are on
53
+ the same filehandle. This means that you cannot pass an uninitialized variable
54
+ for C<$chld_err> and have C<open3> auto-generate a filehandle for you, but
55
+ gensym from L<Symbol> can be used to vivify a new glob reference; see
56
+ L</SYNOPSIS>. The C<$chld_in> handle will have autoflush turned on.
57
+
58
+ By default, the filehandles you pass in are used as output parameters.
59
+ C<open3> internally creates three pipes. The write end of the first pipe and
60
+ the read ends of the other pipes are connected to the command's standard
61
+ input/output/error, respectively. The corresponding read and write ends are
62
+ placed in the first three argument to C<open3>.
63
+
64
+ The filehandle arguments can take the following forms:
65
+
66
+ =over
67
+
68
+ =item *
69
+
70
+ An uninitialized variable (technically, either C<undef> or the empty string
71
+ will work): C<open3> generates a fresh filehandle and assigns it to the
72
+ argument, which must be a modifiable variable for this work (otherwise an
73
+ exception will be raised).
74
+
75
+ This does not work for C<$chld_err>, however: If the C<$chld_err> argument is
76
+ a false value, the child's error stream is automatically redirected to its
77
+ standard output.
78
+
79
+ =item *
80
+
81
+ An existing handle in the form of a typeglob like C<*STDIN> or C<*FOO> or a
82
+ reference to such: C<open3> places the filehandle in the C<IO> slot of the
83
+ typeglob, which means the corresponding bareword filehandle (like C<STDIN> or
84
+ C<FOO>) can be used for I/O from/to the child process. (If the handle is
85
+ already open, it is automatically closed first.)
86
+
87
+ =item *
88
+
89
+ A string containing the name of a bareword handle (like C<'STDIN'> or
90
+ C<'FOO'>): Such strings are resolved to typeglobs at runtime and then act like
91
+ the case described above.
92
+
93
+ =back
94
+
95
+ However, it is possible to make C<open3> use an existing handle directly (as an
96
+ input argument) and skip the creation of a pipe. To do this, the filehandle
97
+ argument must have one of the following two forms:
98
+
99
+ =over
100
+
101
+ =item *
102
+
103
+ An array reference like C<['&', $fh]>, i.e. the first element is the string
104
+ C<'&'> and the second element is the existing handle to use in the child
105
+ process.
106
+
107
+ =item *
108
+
109
+ A string of the form C<< '<&FOO' >> or C<< '>&FOO' >>, i.e. a string starting
110
+ with the two characters C<< <& >> (for input) or C<< >& >> (for output),
111
+ followed by the name of a bareword filehandle. (The string form cannot be used
112
+ with handles stored in variables.)
113
+
114
+ =back
115
+
116
+ If you use this form for C<$chld_in>, the filehandle will be closed in the
117
+ parent process.
118
+
119
+ The filehandles may also be integers, in which case they are understood
120
+ as file descriptors.
121
+
122
+ C<open3> returns the process ID of the child process. It doesn't return on
123
+ failure: it just raises an exception matching C</^open3:/>. However,
124
+ C<exec> failures in the child (such as no such file or permission denied),
125
+ are just reported to C<$chld_err> under Windows and OS/2, as it is not possible
126
+ to trap them.
127
+
128
+ If the child process dies for any reason, the next write to C<$chld_in> is
129
+ likely to generate a SIGPIPE in the parent, which is fatal by default,
130
+ So you may wish to handle this signal.
131
+
132
+ Note: if you specify C<-> as the command, in an analogous fashion to
133
+ C<open(my $fh, "-|")> the child process will just be the forked Perl
134
+ process rather than an external command. This feature isn't yet
135
+ supported on Win32 platforms.
136
+
137
+ C<open3> does not wait for and reap the child process after it exits.
138
+ Except for short programs where it's acceptable to let the operating system
139
+ take care of this, you need to do this yourself. This is normally as
140
+ simple as calling C<waitpid $pid, 0> when you're done with the process.
141
+ Failing to do this can result in an accumulation of defunct or "zombie"
142
+ processes. See L<perlfunc/waitpid> for more information.
143
+
144
+ If you try to read from the child's stdout writer and their stderr
145
+ writer, you'll have problems with blocking, which means you'll want
146
+ to use C<select> or L<IO::Select>, which means you'd best use
147
+ C<sysread> instead of C<readline> for normal stuff.
148
+
149
+ This is very dangerous, as you may block forever. C<open3> assumes it's
150
+ going to talk to something like L<bc(1)>, both writing to it and reading
151
+ from it. This is presumably safe because you "know" that commands
152
+ like L<bc(1)> will read a line at a time and output a line at a time.
153
+ Programs like L<sort(1)> that read their entire input stream first,
154
+ however, are quite apt to cause deadlock.
155
+
156
+ The big problem with this approach is that if you don't have control
157
+ over source code being run in the child process, you can't control
158
+ what it does with pipe buffering. Thus you can't just open a pipe to
159
+ C<cat -v> and continually read and write a line from it.
160
+
161
+ =head1 See Also
162
+
163
+ =over 4
164
+
165
+ =item L<IPC::Open2>
166
+
167
+ Like L<IPC::Open3> but without C<STDERR> capture.
168
+
169
+ =item L<IPC::Run>
170
+
171
+ This is a CPAN module that has better error handling and more facilities
172
+ than L<IPC::Open3>.
173
+
174
+ =back
175
+
176
+ =head1 WARNING
177
+
178
+ The order of arguments differs from that of C<open2>.
179
+
180
+ =cut
181
+
182
+ # &open3: Marc Horowitz <marc@mit.edu>
183
+ # derived mostly from &open2 by tom christiansen, <tchrist@convex.com>
184
+ # fixed for 5.001 by Ulrich Kunitz <kunitz@mai-koeln.com>
185
+ # ported to Win32 by Ron Schmidt, Merrill Lynch almost ended my career
186
+ # fixed for autovivving FHs, tchrist again
187
+ # allow fd numbers to be used, by Frank Tobin
188
+ # allow '-' as command (c.f. open "-|"), by Adam Spiers <perl@adamspiers.org>
189
+ #
190
+ # usage: $pid = open3('wtr', 'rdr', 'err' 'some cmd and args', 'optarg', ...);
191
+ #
192
+ # spawn the given $cmd and connect rdr for
193
+ # reading, wtr for writing, and err for errors.
194
+ # if err is '', or the same as rdr, then stdout and
195
+ # stderr of the child are on the same fh. returns pid
196
+ # of child (or dies on failure).
197
+
198
+
199
+ # if wtr begins with '<&', then wtr will be closed in the parent, and
200
+ # the child will read from it directly. if rdr or err begins with
201
+ # '>&', then the child will send output directly to that fd. In both
202
+ # cases, there will be a dup() instead of a pipe() made.
203
+
204
+
205
+ # WARNING: this is dangerous, as you may block forever
206
+ # unless you are very careful.
207
+ #
208
+ # $wtr is left unbuffered.
209
+ #
210
+ # abort program if
211
+ # rdr or wtr are null
212
+ # a system call fails
213
+
214
+ our $Me = 'open3 (bug)'; # you should never see this, it's always localized
215
+
216
+ # Fatal.pm needs to be fixed WRT prototypes.
217
+
218
+ sub xpipe {
219
+ pipe $_[0], $_[1] or croak "$Me: pipe($_[0], $_[1]) failed: $!";
220
+ }
221
+
222
+ # I tried using a * prototype character for the filehandle but it still
223
+ # disallows a bareword while compiling under strict subs.
224
+
225
+ sub xopen {
226
+ open $_[0], $_[1], @_[2..$#_] and return;
227
+ local $" = ', ';
228
+ carp "$Me: open(@_) failed: $!";
229
+ }
230
+
231
+ sub xclose {
232
+ $_[0] =~ /\A=?(\d+)\z/
233
+ ? do { my $fh; open($fh, $_[1] . '&=' . $1) and close($fh); }
234
+ : close $_[0]
235
+ or croak "$Me: close($_[0]) failed: $!";
236
+ }
237
+
238
+ sub xfileno {
239
+ return $1 if $_[0] =~ /\A=?(\d+)\z/; # deal with fh just being an fd
240
+ return fileno $_[0];
241
+ }
242
+
243
+ use constant FORCE_DEBUG_SPAWN => 0;
244
+ use constant DO_SPAWN => $^O eq 'os2' || $^O eq 'MSWin32' || FORCE_DEBUG_SPAWN;
245
+
246
+ sub _open3 {
247
+ local $Me = shift;
248
+
249
+ # simulate autovivification of filehandles because
250
+ # it's too ugly to use @_ throughout to make perl do it for us
251
+ # tchrist 5-Mar-00
252
+
253
+ # Historically, open3(undef...) has silently worked, so keep
254
+ # it working.
255
+ splice @_, 0, 1, undef if \$_[0] == \undef;
256
+ splice @_, 1, 1, undef if \$_[1] == \undef;
257
+ unless (eval {
258
+ $_[0] = gensym unless defined $_[0] && length $_[0];
259
+ $_[1] = gensym unless defined $_[1] && length $_[1];
260
+ 1; })
261
+ {
262
+ # must strip crud for croak to add back, or looks ugly
263
+ $@ =~ s/(?<=value attempted) at .*//s;
264
+ croak "$Me: $@";
265
+ }
266
+
267
+ my @handles = ({ mode => '<', handle => \*STDIN },
268
+ { mode => '>', handle => \*STDOUT },
269
+ { mode => '>', handle => \*STDERR },
270
+ );
271
+
272
+ foreach (@handles) {
273
+ $_->{parent} = shift;
274
+ $_->{open_as} = gensym;
275
+ }
276
+
277
+ if (@_ > 1 and $_[0] eq '-') {
278
+ croak "Arguments don't make sense when the command is '-'"
279
+ }
280
+
281
+ $handles[2]{parent} ||= $handles[1]{parent};
282
+ $handles[2]{dup_of_out} = $handles[1]{parent} eq $handles[2]{parent};
283
+
284
+ my $package;
285
+ foreach (@handles) {
286
+ if (ref($_->{parent}) eq 'ARRAY') {
287
+ if ($_->{parent}[0] eq '&') {
288
+ $_->{dup} = 1;
289
+ $_->{parent} = $_->{parent}[1];
290
+ } else {
291
+ croak "$Me: Invalid dup mode: $_->{parent}[0]";
292
+ }
293
+ } else {
294
+ $_->{dup} = ($_->{parent} =~ s/^[<>]&//);
295
+
296
+ if ($_->{parent} !~ /\A=?(\d+)\z/) {
297
+ # force unqualified filehandles into caller's package
298
+ $package //= caller 1;
299
+ $_->{parent} = qualify $_->{parent}, $package;
300
+ }
301
+
302
+ next if $_->{dup} or $_->{dup_of_out};
303
+ if ($_->{mode} eq '<') {
304
+ xpipe $_->{open_as}, $_->{parent};
305
+ } else {
306
+ xpipe $_->{parent}, $_->{open_as};
307
+ }
308
+ }
309
+ }
310
+
311
+ my $kidpid;
312
+ if (!DO_SPAWN) {
313
+ # Used to communicate exec failures.
314
+ xpipe my $stat_r, my $stat_w;
315
+
316
+ $kidpid = fork;
317
+ croak "$Me: fork failed: $!" unless defined $kidpid;
318
+ if ($kidpid == 0) { # Kid
319
+ eval {
320
+ # A tie in the parent should not be allowed to cause problems.
321
+ untie *STDIN;
322
+ untie *STDOUT;
323
+ untie *STDERR;
324
+
325
+ close $stat_r;
326
+ require Fcntl;
327
+ my $flags = fcntl $stat_w, &Fcntl::F_GETFD, 0;
328
+ croak "$Me: fcntl failed: $!" unless $flags;
329
+ fcntl $stat_w, &Fcntl::F_SETFD, $flags|&Fcntl::FD_CLOEXEC
330
+ or croak "$Me: fcntl failed: $!";
331
+
332
+ # If she wants to dup the kid's stderr onto her stdout I need to
333
+ # save a copy of her stdout before I put something else there.
334
+ if (!$handles[2]{dup_of_out} && $handles[2]{dup}
335
+ && xfileno($handles[2]{parent}) == fileno \*STDOUT) {
336
+ my $tmp = gensym;
337
+ xopen($tmp, '>&', $handles[2]{parent});
338
+ $handles[2]{parent} = $tmp;
339
+ }
340
+
341
+ foreach (@handles) {
342
+ if ($_->{dup_of_out}) {
343
+ xopen \*STDERR, '>&', *STDOUT
344
+ if defined fileno STDERR && fileno STDERR != fileno STDOUT;
345
+ } elsif ($_->{dup}) {
346
+ xopen $_->{handle}, $_->{mode} . '&', $_->{parent}
347
+ if fileno $_->{handle} != xfileno($_->{parent});
348
+ } else {
349
+ xclose $_->{parent}, $_->{mode};
350
+ xopen $_->{handle}, $_->{mode} . '&=',
351
+ fileno $_->{open_as};
352
+ }
353
+ }
354
+ return 1 if ($_[0] eq '-');
355
+ exec @_ or do {
356
+ local($")=(" ");
357
+ croak "$Me: exec of @_ failed: $!";
358
+ };
359
+ } and do {
360
+ close $stat_w;
361
+ return 0;
362
+ };
363
+
364
+ my $bang = 0+$!;
365
+ my $err = $@;
366
+ utf8::encode $err if $] >= 5.008;
367
+ print $stat_w pack('IIa*', $bang, length($err), $err);
368
+ close $stat_w;
369
+
370
+ eval { require POSIX; POSIX::_exit(255); };
371
+ exit 255;
372
+ }
373
+ else { # Parent
374
+ close $stat_w;
375
+ my $to_read = length(pack('I', 0)) * 2;
376
+ my $bytes_read = read($stat_r, my $buf = '', $to_read);
377
+ if ($bytes_read) {
378
+ (my $bang, $to_read) = unpack('II', $buf);
379
+ read($stat_r, my $err = '', $to_read);
380
+ waitpid $kidpid, 0; # Reap child which should have exited
381
+ if ($err) {
382
+ utf8::decode $err if $] >= 5.008;
383
+ } else {
384
+ $err = "$Me: " . ($! = $bang);
385
+ }
386
+ $! = $bang;
387
+ die($err);
388
+ }
389
+ }
390
+ }
391
+ else { # DO_SPAWN
392
+ # All the bookkeeping of coincidence between handles is
393
+ # handled in spawn_with_handles.
394
+
395
+ my @close;
396
+
397
+ foreach (@handles) {
398
+ if ($_->{dup_of_out}) {
399
+ $_->{open_as} = $handles[1]{open_as};
400
+ } elsif ($_->{dup}) {
401
+ $_->{open_as} = $_->{parent} =~ /\A[0-9]+\z/
402
+ ? $_->{parent} : \*{$_->{parent}};
403
+ push @close, $_->{open_as};
404
+ } else {
405
+ push @close, \*{$_->{parent}}, $_->{open_as};
406
+ }
407
+ }
408
+ require IO::Pipe;
409
+ $kidpid = eval {
410
+ spawn_with_handles(\@handles, \@close, @_);
411
+ };
412
+ die "$Me: $@" if $@;
413
+ }
414
+
415
+ foreach (@handles) {
416
+ next if $_->{dup} or $_->{dup_of_out};
417
+ xclose $_->{open_as}, $_->{mode};
418
+ }
419
+
420
+ # If the write handle is a dup give it away entirely, close my copy
421
+ # of it.
422
+ xclose $handles[0]{parent}, $handles[0]{mode} if $handles[0]{dup};
423
+
424
+ select((select($handles[0]{parent}), $| = 1)[0]); # unbuffer pipe
425
+ $kidpid;
426
+ }
427
+
428
+ sub open3 {
429
+ if (@_ < 4) {
430
+ local $" = ', ';
431
+ croak "open3(@_): not enough arguments";
432
+ }
433
+ return _open3 'open3', @_
434
+ }
435
+
436
+ sub spawn_with_handles {
437
+ my $fds = shift; # Fields: handle, mode, open_as
438
+ my $close_in_child = shift;
439
+ my ($fd, %saved, @errs);
440
+
441
+ foreach $fd (@$fds) {
442
+ $fd->{tmp_copy} = IO::Handle->new_from_fd($fd->{handle}, $fd->{mode});
443
+ $saved{fileno $fd->{handle}} = $fd->{tmp_copy} if $fd->{tmp_copy};
444
+ }
445
+ foreach $fd (@$fds) {
446
+ bless $fd->{handle}, 'IO::Handle'
447
+ unless eval { $fd->{handle}->isa('IO::Handle') } ;
448
+ # If some of handles to redirect-to coincide with handles to
449
+ # redirect, we need to use saved variants:
450
+ my $open_as = $fd->{open_as};
451
+ my $fileno = fileno($open_as);
452
+ $fd->{handle}->fdopen(defined($fileno)
453
+ ? $saved{$fileno} || $open_as
454
+ : $open_as,
455
+ $fd->{mode});
456
+ }
457
+ unless ($^O eq 'MSWin32') {
458
+ require Fcntl;
459
+ # Stderr may be redirected below, so we save the err text:
460
+ foreach $fd (@$close_in_child) {
461
+ next unless fileno $fd;
462
+ fcntl($fd, Fcntl::F_SETFD(), 1) or push @errs, "fcntl $fd: $!"
463
+ unless $saved{fileno $fd}; # Do not close what we redirect!
464
+ }
465
+ }
466
+
467
+ my $pid;
468
+ unless (@errs) {
469
+ if (FORCE_DEBUG_SPAWN) {
470
+ pipe my $r, my $w or die "Pipe failed: $!";
471
+ $pid = fork;
472
+ die "Fork failed: $!" unless defined $pid;
473
+ if (!$pid) {
474
+ { no warnings; exec @_ }
475
+ print $w 0 + $!;
476
+ close $w;
477
+ require POSIX;
478
+ POSIX::_exit(255);
479
+ }
480
+ close $w;
481
+ my $bad = <$r>;
482
+ if (defined $bad) {
483
+ $! = $bad;
484
+ undef $pid;
485
+ }
486
+ } else {
487
+ $pid = eval { system 1, @_ }; # 1 == P_NOWAIT
488
+ }
489
+ if($@) {
490
+ push @errs, "IO::Pipe: Can't spawn-NOWAIT: $@";
491
+ } elsif(!$pid || $pid < 0) {
492
+ push @errs, "IO::Pipe: Can't spawn-NOWAIT: $!";
493
+ }
494
+ }
495
+
496
+ # Do this in reverse, so that STDERR is restored first:
497
+ foreach $fd (reverse @$fds) {
498
+ $fd->{handle}->fdopen($fd->{tmp_copy}, $fd->{mode});
499
+ }
500
+ foreach (values %saved) {
501
+ $_->close or croak "Can't close: $!";
502
+ }
503
+ croak join "\n", @errs if @errs;
504
+ return $pid;
505
+ }
506
+
507
+ 1; # so require is happy
git/usr/share/perl5/core_perl/JSON/PP.pm ADDED
The diff for this file is too large to render. See raw diff
 
git/usr/share/perl5/core_perl/Math/BigFloat.pm ADDED
The diff for this file is too large to render. See raw diff
 
git/usr/share/perl5/core_perl/Math/BigInt.pm ADDED
The diff for this file is too large to render. See raw diff
 
git/usr/share/perl5/core_perl/Math/BigRat.pm ADDED
The diff for this file is too large to render. See raw diff
 
git/usr/share/perl5/core_perl/Math/Complex.pm ADDED
@@ -0,0 +1,2138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # Complex numbers and associated mathematical functions
3
+ # -- Raphael Manfredi Since Sep 1996
4
+ # -- Jarkko Hietaniemi Since Mar 1997
5
+ # -- Daniel S. Lewart Since Sep 1997
6
+ #
7
+
8
+ package Math::Complex;
9
+
10
+ { use 5.006; }
11
+ use strict;
12
+
13
+ our $VERSION = 1.63;
14
+
15
+ use Config;
16
+
17
+ our ($Inf, $ExpInf);
18
+ our ($vax_float, $has_inf, $has_nan);
19
+
20
+ BEGIN {
21
+ $vax_float = (pack("d",1) =~ /^[\x80\x10]\x40/);
22
+ $has_inf = !$vax_float;
23
+ $has_nan = !$vax_float;
24
+
25
+ unless ($has_inf) {
26
+ # For example in vax, there is no Inf,
27
+ # and just mentioning the DBL_MAX (1.70141183460469229e+38)
28
+ # causes SIGFPE.
29
+
30
+ # These are pretty useless without a real infinity,
31
+ # but setting them makes for less warnings about their
32
+ # undefined values.
33
+ $Inf = "Inf";
34
+ $ExpInf = "Inf";
35
+ return;
36
+ }
37
+
38
+ my %DBL_MAX = # These are IEEE 754 maxima.
39
+ (
40
+ 4 => '1.70141183460469229e+38',
41
+ 8 => '1.7976931348623157e+308',
42
+ # AFAICT the 10, 12, and 16-byte long doubles
43
+ # all have the same maximum.
44
+ 10 => '1.1897314953572317650857593266280070162E+4932',
45
+ 12 => '1.1897314953572317650857593266280070162E+4932',
46
+ 16 => '1.1897314953572317650857593266280070162E+4932',
47
+ );
48
+
49
+ my $nvsize = $Config{nvsize} ||
50
+ ($Config{uselongdouble} && $Config{longdblsize}) ||
51
+ $Config{doublesize};
52
+ die "Math::Complex: Could not figure out nvsize\n"
53
+ unless defined $nvsize;
54
+ die "Math::Complex: Cannot not figure out max nv (nvsize = $nvsize)\n"
55
+ unless defined $DBL_MAX{$nvsize};
56
+ my $DBL_MAX = eval $DBL_MAX{$nvsize};
57
+ die "Math::Complex: Could not figure out max nv (nvsize = $nvsize)\n"
58
+ unless defined $DBL_MAX;
59
+ my $BIGGER_THAN_THIS = 1e30; # Must find something bigger than this.
60
+ if ($^O eq 'unicosmk') {
61
+ $Inf = $DBL_MAX;
62
+ } else {
63
+ local $SIG{FPE} = sub { };
64
+ local $!;
65
+ # We do want an arithmetic overflow, Inf INF inf Infinity.
66
+ for my $t (
67
+ 'exp(99999)', # Enough even with 128-bit long doubles.
68
+ 'inf',
69
+ 'Inf',
70
+ 'INF',
71
+ 'infinity',
72
+ 'Infinity',
73
+ 'INFINITY',
74
+ '1e99999',
75
+ ) {
76
+ local $^W = 0;
77
+ my $i = eval "$t+1.0";
78
+ if (defined $i && $i > $BIGGER_THAN_THIS) {
79
+ $Inf = $i;
80
+ last;
81
+ }
82
+ }
83
+ $Inf = $DBL_MAX unless defined $Inf; # Oh well, close enough.
84
+ die "Math::Complex: Could not get Infinity"
85
+ unless $Inf > $BIGGER_THAN_THIS;
86
+ $ExpInf = eval 'exp(99999)';
87
+ }
88
+ # print "# On this machine, Inf = '$Inf'\n";
89
+ }
90
+
91
+ use Scalar::Util qw(set_prototype);
92
+
93
+ use warnings;
94
+ no warnings 'syntax'; # To avoid the (_) warnings.
95
+
96
+ BEGIN {
97
+ # For certain functions that we override, in 5.10 or better
98
+ # we can set a smarter prototype that will handle the lexical $_
99
+ # (also a 5.10+ feature).
100
+ if ($] >= 5.010000) {
101
+ set_prototype \&abs, '_';
102
+ set_prototype \&cos, '_';
103
+ set_prototype \&exp, '_';
104
+ set_prototype \&log, '_';
105
+ set_prototype \&sin, '_';
106
+ set_prototype \&sqrt, '_';
107
+ }
108
+ }
109
+
110
+ my $i;
111
+ my %LOGN;
112
+
113
+ # Regular expression for floating point numbers.
114
+ # These days we could use Scalar::Util::lln(), I guess.
115
+ my $gre = qr'\s*([\+\-]?(?:(?:(?:\d+(?:_\d+)*(?:\.\d*(?:_\d+)*)?|\.\d+(?:_\d+)*)(?:[eE][\+\-]?\d+(?:_\d+)*)?)|inf))'i;
116
+
117
+ require Exporter;
118
+
119
+ our @ISA = qw(Exporter);
120
+
121
+ my @trig = qw(
122
+ pi
123
+ tan
124
+ csc cosec sec cot cotan
125
+ asin acos atan
126
+ acsc acosec asec acot acotan
127
+ sinh cosh tanh
128
+ csch cosech sech coth cotanh
129
+ asinh acosh atanh
130
+ acsch acosech asech acoth acotanh
131
+ );
132
+
133
+ our @EXPORT = (qw(
134
+ i Re Im rho theta arg
135
+ sqrt log ln
136
+ log10 logn cbrt root
137
+ cplx cplxe
138
+ atan2
139
+ ),
140
+ @trig);
141
+
142
+ my @pi = qw(pi pi2 pi4 pip2 pip4 Inf);
143
+
144
+ our @EXPORT_OK = @pi;
145
+
146
+ our %EXPORT_TAGS = (
147
+ 'trig' => [@trig],
148
+ 'pi' => [@pi],
149
+ );
150
+
151
+ use overload
152
+ '=' => \&_copy,
153
+ '+=' => \&_plus,
154
+ '+' => \&_plus,
155
+ '-=' => \&_minus,
156
+ '-' => \&_minus,
157
+ '*=' => \&_multiply,
158
+ '*' => \&_multiply,
159
+ '/=' => \&_divide,
160
+ '/' => \&_divide,
161
+ '**=' => \&_power,
162
+ '**' => \&_power,
163
+ '==' => \&_numeq,
164
+ '<=>' => \&_spaceship,
165
+ 'neg' => \&_negate,
166
+ '~' => \&_conjugate,
167
+ 'abs' => \&abs,
168
+ 'sqrt' => \&sqrt,
169
+ 'exp' => \&exp,
170
+ 'log' => \&log,
171
+ 'sin' => \&sin,
172
+ 'cos' => \&cos,
173
+ 'atan2' => \&atan2,
174
+ '""' => \&_stringify;
175
+
176
+ #
177
+ # Package "privates"
178
+ #
179
+
180
+ my %DISPLAY_FORMAT = ('style' => 'cartesian',
181
+ 'polar_pretty_print' => 1);
182
+ my $eps = 1e-14; # Epsilon
183
+
184
+ #
185
+ # Object attributes (internal):
186
+ # cartesian [real, imaginary] -- cartesian form
187
+ # polar [rho, theta] -- polar form
188
+ # c_dirty cartesian form not up-to-date
189
+ # p_dirty polar form not up-to-date
190
+ # display display format (package's global when not set)
191
+ #
192
+
193
+ # Die on bad *make() arguments.
194
+
195
+ sub _cannot_make {
196
+ die "@{[(caller(1))[3]]}: Cannot take $_[0] of '$_[1]'.\n";
197
+ }
198
+
199
+ sub _normalize_num {
200
+ my $x = shift;
201
+ $x =~ s/^\+//;
202
+ $x =~ s/_//g;
203
+ $x =~ s/^(-?)inf$/$1 ? -Inf() : Inf()/ie if $has_inf;
204
+ return $x;
205
+ }
206
+
207
+ sub _make {
208
+ my $arg = shift;
209
+ my ($p, $q);
210
+
211
+ if ($arg =~ /^$gre$/) {
212
+ ($p, $q) = ($1, 0);
213
+ } elsif ($arg =~ /^(?:$gre(?=\s*[+\-]))?$gre\s*i\s*$/) {
214
+ ($p, $q) = ($1 || 0, $2);
215
+ } elsif ($arg =~ /^(?:$gre(?=\s*[+\-]))?\s*([+\-]?)i\s*$/) {
216
+ ($p, $q) = ($1 || 0, $2 . '1');
217
+ } elsif ($arg =~ /^\s*\($gre\s*(?:,$gre\s*)?\)\s*$/) {
218
+ ($p, $q) = ($1, $2 || 0);
219
+ }
220
+
221
+ if (defined $p) {
222
+ $p = _normalize_num $p;
223
+ $q = _normalize_num $q;
224
+ }
225
+
226
+ return ($p, $q);
227
+ }
228
+
229
+ sub _emake {
230
+ my $arg = shift;
231
+ my ($p, $q);
232
+
233
+ if ($arg =~ /^\s*\[$gre\s*(?:,$gre\s*)?\]\s*$/) {
234
+ ($p, $q) = ($1, $2 || 0);
235
+ } elsif ($arg =~ m!^\s*\[$gre\s*(?:,\s*([-+]?\d*\s*)?pi(?:/\s*(\d+))?\s*)?\]\s*$!) {
236
+ ($p, $q) = ($1, ($2 eq '-' ? -1 : ($2 || 1)) * pi() / ($3 || 1));
237
+ } elsif ($arg =~ /^\s*\[$gre\s*\]\s*$/) {
238
+ ($p, $q) = ($1, 0);
239
+ } elsif ($arg =~ /^$gre\s*$/) {
240
+ ($p, $q) = ($1, 0);
241
+ }
242
+
243
+ if (defined $p) {
244
+ $p = _normalize_num $p;
245
+ $q = _normalize_num $q;
246
+ }
247
+
248
+ return ($p, $q);
249
+ }
250
+
251
+ sub _copy {
252
+ my $self = shift;
253
+ my $clone = {%$self};
254
+ if ($self->{'cartesian'}) {
255
+ $clone->{'cartesian'} = [@{$self->{'cartesian'}}];
256
+ }
257
+ if ($self->{'polar'}) {
258
+ $clone->{'polar'} = [@{$self->{'polar'}}];
259
+ }
260
+ bless $clone,__PACKAGE__;
261
+ return $clone;
262
+ }
263
+
264
+ #
265
+ # ->make
266
+ #
267
+ # Create a new complex number (cartesian form)
268
+ #
269
+ sub make {
270
+ my $self = bless {}, shift;
271
+ my ($re, $im);
272
+ if (@_ == 0) {
273
+ ($re, $im) = (0, 0);
274
+ } elsif (@_ == 1) {
275
+ return (ref $self)->emake($_[0])
276
+ if ($_[0] =~ /^\s*\[/);
277
+ ($re, $im) = _make($_[0]);
278
+ } elsif (@_ == 2) {
279
+ ($re, $im) = @_;
280
+ }
281
+ if (defined $re) {
282
+ _cannot_make("real part", $re) unless $re =~ /^$gre$/;
283
+ }
284
+ $im ||= 0;
285
+ _cannot_make("imaginary part", $im) unless $im =~ /^$gre$/;
286
+ $self->_set_cartesian([$re, $im ]);
287
+ $self->display_format('cartesian');
288
+
289
+ return $self;
290
+ }
291
+
292
+ #
293
+ # ->emake
294
+ #
295
+ # Create a new complex number (exponential form)
296
+ #
297
+ sub emake {
298
+ my $self = bless {}, shift;
299
+ my ($rho, $theta);
300
+ if (@_ == 0) {
301
+ ($rho, $theta) = (0, 0);
302
+ } elsif (@_ == 1) {
303
+ return (ref $self)->make($_[0])
304
+ if ($_[0] =~ /^\s*\(/ || $_[0] =~ /i\s*$/);
305
+ ($rho, $theta) = _emake($_[0]);
306
+ } elsif (@_ == 2) {
307
+ ($rho, $theta) = @_;
308
+ }
309
+ if (defined $rho && defined $theta) {
310
+ if ($rho < 0) {
311
+ $rho = -$rho;
312
+ $theta = ($theta <= 0) ? $theta + pi() : $theta - pi();
313
+ }
314
+ }
315
+ if (defined $rho) {
316
+ _cannot_make("rho", $rho) unless $rho =~ /^$gre$/;
317
+ }
318
+ $theta ||= 0;
319
+ _cannot_make("theta", $theta) unless $theta =~ /^$gre$/;
320
+ $self->_set_polar([$rho, $theta]);
321
+ $self->display_format('polar');
322
+
323
+ return $self;
324
+ }
325
+
326
+ sub new { &make } # For backward compatibility only.
327
+
328
+ #
329
+ # cplx
330
+ #
331
+ # Creates a complex number from a (re, im) tuple.
332
+ # This avoids the burden of writing Math::Complex->make(re, im).
333
+ #
334
+ sub cplx {
335
+ return __PACKAGE__->make(@_);
336
+ }
337
+
338
+ #
339
+ # cplxe
340
+ #
341
+ # Creates a complex number from a (rho, theta) tuple.
342
+ # This avoids the burden of writing Math::Complex->emake(rho, theta).
343
+ #
344
+ sub cplxe {
345
+ return __PACKAGE__->emake(@_);
346
+ }
347
+
348
+ #
349
+ # pi
350
+ #
351
+ # The number defined as pi = 180 degrees
352
+ #
353
+ sub pi () { 4 * CORE::atan2(1, 1) }
354
+
355
+ #
356
+ # pi2
357
+ #
358
+ # The full circle
359
+ #
360
+ sub pi2 () { 2 * pi }
361
+
362
+ #
363
+ # pi4
364
+ #
365
+ # The full circle twice.
366
+ #
367
+ sub pi4 () { 4 * pi }
368
+
369
+ #
370
+ # pip2
371
+ #
372
+ # The quarter circle
373
+ #
374
+ sub pip2 () { pi / 2 }
375
+
376
+ #
377
+ # pip4
378
+ #
379
+ # The eighth circle.
380
+ #
381
+ sub pip4 () { pi / 4 }
382
+
383
+ #
384
+ # _uplog10
385
+ #
386
+ # Used in log10().
387
+ #
388
+ sub _uplog10 () { 1 / CORE::log(10) }
389
+
390
+ #
391
+ # i
392
+ #
393
+ # The number defined as i*i = -1;
394
+ #
395
+ sub i () {
396
+ return $i if ($i);
397
+ $i = bless {};
398
+ $i->{'cartesian'} = [0, 1];
399
+ $i->{'polar'} = [1, pip2];
400
+ $i->{c_dirty} = 0;
401
+ $i->{p_dirty} = 0;
402
+ return $i;
403
+ }
404
+
405
+ #
406
+ # _ip2
407
+ #
408
+ # Half of i.
409
+ #
410
+ sub _ip2 () { i / 2 }
411
+
412
+ #
413
+ # Attribute access/set routines
414
+ #
415
+
416
+ sub _cartesian {$_[0]->{c_dirty} ?
417
+ $_[0]->_update_cartesian : $_[0]->{'cartesian'}}
418
+ sub _polar {$_[0]->{p_dirty} ?
419
+ $_[0]->_update_polar : $_[0]->{'polar'}}
420
+
421
+ sub _set_cartesian { $_[0]->{p_dirty}++; $_[0]->{c_dirty} = 0;
422
+ $_[0]->{'cartesian'} = $_[1] }
423
+ sub _set_polar { $_[0]->{c_dirty}++; $_[0]->{p_dirty} = 0;
424
+ $_[0]->{'polar'} = $_[1] }
425
+
426
+ #
427
+ # ->_update_cartesian
428
+ #
429
+ # Recompute and return the cartesian form, given accurate polar form.
430
+ #
431
+ sub _update_cartesian {
432
+ my $self = shift;
433
+ my ($r, $t) = @{$self->{'polar'}};
434
+ $self->{c_dirty} = 0;
435
+ return $self->{'cartesian'} = [$r * CORE::cos($t), $r * CORE::sin($t)];
436
+ }
437
+
438
+ #
439
+ #
440
+ # ->_update_polar
441
+ #
442
+ # Recompute and return the polar form, given accurate cartesian form.
443
+ #
444
+ sub _update_polar {
445
+ my $self = shift;
446
+ my ($x, $y) = @{$self->{'cartesian'}};
447
+ $self->{p_dirty} = 0;
448
+ return $self->{'polar'} = [0, 0] if $x == 0 && $y == 0;
449
+ return $self->{'polar'} = [CORE::sqrt($x*$x + $y*$y),
450
+ CORE::atan2($y, $x)];
451
+ }
452
+
453
+ #
454
+ # (_plus)
455
+ #
456
+ # Computes z1+z2.
457
+ #
458
+ sub _plus {
459
+ my ($z1, $z2, $regular) = @_;
460
+ my ($re1, $im1) = @{$z1->_cartesian};
461
+ $z2 = cplx($z2) unless ref $z2;
462
+ my ($re2, $im2) = ref $z2 ? @{$z2->_cartesian} : ($z2, 0);
463
+ unless (defined $regular) {
464
+ $z1->_set_cartesian([$re1 + $re2, $im1 + $im2]);
465
+ return $z1;
466
+ }
467
+ return (ref $z1)->make($re1 + $re2, $im1 + $im2);
468
+ }
469
+
470
+ #
471
+ # (_minus)
472
+ #
473
+ # Computes z1-z2.
474
+ #
475
+ sub _minus {
476
+ my ($z1, $z2, $inverted) = @_;
477
+ my ($re1, $im1) = @{$z1->_cartesian};
478
+ $z2 = cplx($z2) unless ref $z2;
479
+ my ($re2, $im2) = @{$z2->_cartesian};
480
+ unless (defined $inverted) {
481
+ $z1->_set_cartesian([$re1 - $re2, $im1 - $im2]);
482
+ return $z1;
483
+ }
484
+ return $inverted ?
485
+ (ref $z1)->make($re2 - $re1, $im2 - $im1) :
486
+ (ref $z1)->make($re1 - $re2, $im1 - $im2);
487
+
488
+ }
489
+
490
+ #
491
+ # (_multiply)
492
+ #
493
+ # Computes z1*z2.
494
+ #
495
+ sub _multiply {
496
+ my ($z1, $z2, $regular) = @_;
497
+ if ($z1->{p_dirty} == 0 and ref $z2 and $z2->{p_dirty} == 0) {
498
+ # if both polar better use polar to avoid rounding errors
499
+ my ($r1, $t1) = @{$z1->_polar};
500
+ my ($r2, $t2) = @{$z2->_polar};
501
+ my $t = $t1 + $t2;
502
+ if ($t > pi()) { $t -= pi2 }
503
+ elsif ($t <= -pi()) { $t += pi2 }
504
+ unless (defined $regular) {
505
+ $z1->_set_polar([$r1 * $r2, $t]);
506
+ return $z1;
507
+ }
508
+ return (ref $z1)->emake($r1 * $r2, $t);
509
+ } else {
510
+ my ($x1, $y1) = @{$z1->_cartesian};
511
+ if (ref $z2) {
512
+ my ($x2, $y2) = @{$z2->_cartesian};
513
+ return (ref $z1)->make($x1*$x2-$y1*$y2, $x1*$y2+$y1*$x2);
514
+ } else {
515
+ return (ref $z1)->make($x1*$z2, $y1*$z2);
516
+ }
517
+ }
518
+ }
519
+
520
+ #
521
+ # _divbyzero
522
+ #
523
+ # Die on division by zero.
524
+ #
525
+ sub _divbyzero {
526
+ my $mess = "$_[0]: Division by zero.\n";
527
+
528
+ if (defined $_[1]) {
529
+ $mess .= "(Because in the definition of $_[0], the divisor ";
530
+ $mess .= "$_[1] " unless ("$_[1]" eq '0');
531
+ $mess .= "is 0)\n";
532
+ }
533
+
534
+ my @up = caller(1);
535
+
536
+ $mess .= "Died at $up[1] line $up[2].\n";
537
+
538
+ die $mess;
539
+ }
540
+
541
+ #
542
+ # (_divide)
543
+ #
544
+ # Computes z1/z2.
545
+ #
546
+ sub _divide {
547
+ my ($z1, $z2, $inverted) = @_;
548
+ if ($z1->{p_dirty} == 0 and ref $z2 and $z2->{p_dirty} == 0) {
549
+ # if both polar better use polar to avoid rounding errors
550
+ my ($r1, $t1) = @{$z1->_polar};
551
+ my ($r2, $t2) = @{$z2->_polar};
552
+ my $t;
553
+ if ($inverted) {
554
+ _divbyzero "$z2/0" if ($r1 == 0);
555
+ $t = $t2 - $t1;
556
+ if ($t > pi()) { $t -= pi2 }
557
+ elsif ($t <= -pi()) { $t += pi2 }
558
+ return (ref $z1)->emake($r2 / $r1, $t);
559
+ } else {
560
+ _divbyzero "$z1/0" if ($r2 == 0);
561
+ $t = $t1 - $t2;
562
+ if ($t > pi()) { $t -= pi2 }
563
+ elsif ($t <= -pi()) { $t += pi2 }
564
+ return (ref $z1)->emake($r1 / $r2, $t);
565
+ }
566
+ } else {
567
+ my ($d, $x2, $y2);
568
+ if ($inverted) {
569
+ ($x2, $y2) = @{$z1->_cartesian};
570
+ $d = $x2*$x2 + $y2*$y2;
571
+ _divbyzero "$z2/0" if $d == 0;
572
+ return (ref $z1)->make(($x2*$z2)/$d, -($y2*$z2)/$d);
573
+ } else {
574
+ my ($x1, $y1) = @{$z1->_cartesian};
575
+ if (ref $z2) {
576
+ ($x2, $y2) = @{$z2->_cartesian};
577
+ $d = $x2*$x2 + $y2*$y2;
578
+ _divbyzero "$z1/0" if $d == 0;
579
+ my $u = ($x1*$x2 + $y1*$y2)/$d;
580
+ my $v = ($y1*$x2 - $x1*$y2)/$d;
581
+ return (ref $z1)->make($u, $v);
582
+ } else {
583
+ _divbyzero "$z1/0" if $z2 == 0;
584
+ return (ref $z1)->make($x1/$z2, $y1/$z2);
585
+ }
586
+ }
587
+ }
588
+ }
589
+
590
+ #
591
+ # (_power)
592
+ #
593
+ # Computes z1**z2 = exp(z2 * log z1)).
594
+ #
595
+ sub _power {
596
+ my ($z1, $z2, $inverted) = @_;
597
+ if ($inverted) {
598
+ return 1 if $z1 == 0 || $z2 == 1;
599
+ return 0 if $z2 == 0 && Re($z1) > 0;
600
+ } else {
601
+ return 1 if $z2 == 0 || $z1 == 1;
602
+ return 0 if $z1 == 0 && Re($z2) > 0;
603
+ }
604
+ my $w = $inverted ? &exp($z1 * &log($z2))
605
+ : &exp($z2 * &log($z1));
606
+ # If both arguments cartesian, return cartesian, else polar.
607
+ return $z1->{c_dirty} == 0 &&
608
+ (not ref $z2 or $z2->{c_dirty} == 0) ?
609
+ cplx(@{$w->_cartesian}) : $w;
610
+ }
611
+
612
+ #
613
+ # (_spaceship)
614
+ #
615
+ # Computes z1 <=> z2.
616
+ # Sorts on the real part first, then on the imaginary part. Thus 2-4i < 3+8i.
617
+ #
618
+ sub _spaceship {
619
+ my ($z1, $z2, $inverted) = @_;
620
+ my ($re1, $im1) = ref $z1 ? @{$z1->_cartesian} : ($z1, 0);
621
+ my ($re2, $im2) = ref $z2 ? @{$z2->_cartesian} : ($z2, 0);
622
+ my $sgn = $inverted ? -1 : 1;
623
+ return $sgn * ($re1 <=> $re2) if $re1 != $re2;
624
+ return $sgn * ($im1 <=> $im2);
625
+ }
626
+
627
+ #
628
+ # (_numeq)
629
+ #
630
+ # Computes z1 == z2.
631
+ #
632
+ # (Required in addition to _spaceship() because of NaNs.)
633
+ sub _numeq {
634
+ my ($z1, $z2, $inverted) = @_;
635
+ my ($re1, $im1) = ref $z1 ? @{$z1->_cartesian} : ($z1, 0);
636
+ my ($re2, $im2) = ref $z2 ? @{$z2->_cartesian} : ($z2, 0);
637
+ return $re1 == $re2 && $im1 == $im2 ? 1 : 0;
638
+ }
639
+
640
+ #
641
+ # (_negate)
642
+ #
643
+ # Computes -z.
644
+ #
645
+ sub _negate {
646
+ my ($z) = @_;
647
+ if ($z->{c_dirty}) {
648
+ my ($r, $t) = @{$z->_polar};
649
+ $t = ($t <= 0) ? $t + pi : $t - pi;
650
+ return (ref $z)->emake($r, $t);
651
+ }
652
+ my ($re, $im) = @{$z->_cartesian};
653
+ return (ref $z)->make(-$re, -$im);
654
+ }
655
+
656
+ #
657
+ # (_conjugate)
658
+ #
659
+ # Compute complex's _conjugate.
660
+ #
661
+ sub _conjugate {
662
+ my ($z) = @_;
663
+ if ($z->{c_dirty}) {
664
+ my ($r, $t) = @{$z->_polar};
665
+ return (ref $z)->emake($r, -$t);
666
+ }
667
+ my ($re, $im) = @{$z->_cartesian};
668
+ return (ref $z)->make($re, -$im);
669
+ }
670
+
671
+ #
672
+ # (abs)
673
+ #
674
+ # Compute or set complex's norm (rho).
675
+ #
676
+ sub abs {
677
+ my ($z, $rho) = @_ ? @_ : $_;
678
+ unless (ref $z) {
679
+ if (@_ == 2) {
680
+ $_[0] = $_[1];
681
+ } else {
682
+ return CORE::abs($z);
683
+ }
684
+ }
685
+ if (defined $rho) {
686
+ $z->{'polar'} = [ $rho, ${$z->_polar}[1] ];
687
+ $z->{p_dirty} = 0;
688
+ $z->{c_dirty} = 1;
689
+ return $rho;
690
+ } else {
691
+ return ${$z->_polar}[0];
692
+ }
693
+ }
694
+
695
+ sub _theta {
696
+ my $theta = $_[0];
697
+
698
+ if ($$theta > pi()) { $$theta -= pi2 }
699
+ elsif ($$theta <= -pi()) { $$theta += pi2 }
700
+ }
701
+
702
+ #
703
+ # arg
704
+ #
705
+ # Compute or set complex's argument (theta).
706
+ #
707
+ sub arg {
708
+ my ($z, $theta) = @_;
709
+ return $z unless ref $z;
710
+ if (defined $theta) {
711
+ _theta(\$theta);
712
+ $z->{'polar'} = [ ${$z->_polar}[0], $theta ];
713
+ $z->{p_dirty} = 0;
714
+ $z->{c_dirty} = 1;
715
+ } else {
716
+ $theta = ${$z->_polar}[1];
717
+ _theta(\$theta);
718
+ }
719
+ return $theta;
720
+ }
721
+
722
+ #
723
+ # (sqrt)
724
+ #
725
+ # Compute sqrt(z).
726
+ #
727
+ # It is quite tempting to use wantarray here so that in list context
728
+ # sqrt() would return the two solutions. This, however, would
729
+ # break things like
730
+ #
731
+ # print "sqrt(z) = ", sqrt($z), "\n";
732
+ #
733
+ # The two values would be printed side by side without no intervening
734
+ # whitespace, quite confusing.
735
+ # Therefore if you want the two solutions use the root().
736
+ #
737
+ sub sqrt {
738
+ my ($z) = @_ ? $_[0] : $_;
739
+ my ($re, $im) = ref $z ? @{$z->_cartesian} : ($z, 0);
740
+ return $re < 0 ? cplx(0, CORE::sqrt(-$re)) : CORE::sqrt($re)
741
+ if $im == 0;
742
+ my ($r, $t) = @{$z->_polar};
743
+ return (ref $z)->emake(CORE::sqrt($r), $t/2);
744
+ }
745
+
746
+ #
747
+ # cbrt
748
+ #
749
+ # Compute cbrt(z) (cubic root).
750
+ #
751
+ # Why are we not returning three values? The same answer as for sqrt().
752
+ #
753
+ sub cbrt {
754
+ my ($z) = @_;
755
+ return $z < 0 ?
756
+ -CORE::exp(CORE::log(-$z)/3) :
757
+ ($z > 0 ? CORE::exp(CORE::log($z)/3): 0)
758
+ unless ref $z;
759
+ my ($r, $t) = @{$z->_polar};
760
+ return 0 if $r == 0;
761
+ return (ref $z)->emake(CORE::exp(CORE::log($r)/3), $t/3);
762
+ }
763
+
764
+ #
765
+ # _rootbad
766
+ #
767
+ # Die on bad root.
768
+ #
769
+ sub _rootbad {
770
+ my $mess = "Root '$_[0]' illegal, root rank must be positive integer.\n";
771
+
772
+ my @up = caller(1);
773
+
774
+ $mess .= "Died at $up[1] line $up[2].\n";
775
+
776
+ die $mess;
777
+ }
778
+
779
+ #
780
+ # root
781
+ #
782
+ # Computes all nth root for z, returning an array whose size is n.
783
+ # `n' must be a positive integer.
784
+ #
785
+ # The roots are given by (for k = 0..n-1):
786
+ #
787
+ # z^(1/n) = r^(1/n) (cos ((t+2 k pi)/n) + i sin ((t+2 k pi)/n))
788
+ #
789
+ sub root {
790
+ my ($z, $n, $k) = @_;
791
+ _rootbad($n) if ($n < 1 or int($n) != $n);
792
+ my ($r, $t) = ref $z ?
793
+ @{$z->_polar} : (CORE::abs($z), $z >= 0 ? 0 : pi);
794
+ my $theta_inc = pi2 / $n;
795
+ my $rho = $r ** (1/$n);
796
+ my $cartesian = ref $z && $z->{c_dirty} == 0;
797
+ if (@_ == 2) {
798
+ my @root;
799
+ for (my $i = 0, my $theta = $t / $n;
800
+ $i < $n;
801
+ $i++, $theta += $theta_inc) {
802
+ my $w = cplxe($rho, $theta);
803
+ # Yes, $cartesian is loop invariant.
804
+ push @root, $cartesian ? cplx(@{$w->_cartesian}) : $w;
805
+ }
806
+ return @root;
807
+ } elsif (@_ == 3) {
808
+ my $w = cplxe($rho, $t / $n + $k * $theta_inc);
809
+ return $cartesian ? cplx(@{$w->_cartesian}) : $w;
810
+ }
811
+ }
812
+
813
+ #
814
+ # Re
815
+ #
816
+ # Return or set Re(z).
817
+ #
818
+ sub Re {
819
+ my ($z, $Re) = @_;
820
+ return $z unless ref $z;
821
+ if (defined $Re) {
822
+ $z->{'cartesian'} = [ $Re, ${$z->_cartesian}[1] ];
823
+ $z->{c_dirty} = 0;
824
+ $z->{p_dirty} = 1;
825
+ } else {
826
+ return ${$z->_cartesian}[0];
827
+ }
828
+ }
829
+
830
+ #
831
+ # Im
832
+ #
833
+ # Return or set Im(z).
834
+ #
835
+ sub Im {
836
+ my ($z, $Im) = @_;
837
+ return 0 unless ref $z;
838
+ if (defined $Im) {
839
+ $z->{'cartesian'} = [ ${$z->_cartesian}[0], $Im ];
840
+ $z->{c_dirty} = 0;
841
+ $z->{p_dirty} = 1;
842
+ } else {
843
+ return ${$z->_cartesian}[1];
844
+ }
845
+ }
846
+
847
+ #
848
+ # rho
849
+ #
850
+ # Return or set rho(w).
851
+ #
852
+ sub rho {
853
+ Math::Complex::abs(@_);
854
+ }
855
+
856
+ #
857
+ # theta
858
+ #
859
+ # Return or set theta(w).
860
+ #
861
+ sub theta {
862
+ Math::Complex::arg(@_);
863
+ }
864
+
865
+ #
866
+ # (exp)
867
+ #
868
+ # Computes exp(z).
869
+ #
870
+ sub exp {
871
+ my ($z) = @_ ? @_ : $_;
872
+ return CORE::exp($z) unless ref $z;
873
+ my ($x, $y) = @{$z->_cartesian};
874
+ return (ref $z)->emake(CORE::exp($x), $y);
875
+ }
876
+
877
+ #
878
+ # _logofzero
879
+ #
880
+ # Die on logarithm of zero.
881
+ #
882
+ sub _logofzero {
883
+ my $mess = "$_[0]: Logarithm of zero.\n";
884
+
885
+ if (defined $_[1]) {
886
+ $mess .= "(Because in the definition of $_[0], the argument ";
887
+ $mess .= "$_[1] " unless ($_[1] eq '0');
888
+ $mess .= "is 0)\n";
889
+ }
890
+
891
+ my @up = caller(1);
892
+
893
+ $mess .= "Died at $up[1] line $up[2].\n";
894
+
895
+ die $mess;
896
+ }
897
+
898
+ #
899
+ # (log)
900
+ #
901
+ # Compute log(z).
902
+ #
903
+ sub log {
904
+ my ($z) = @_ ? @_ : $_;
905
+ unless (ref $z) {
906
+ _logofzero("log") if $z == 0;
907
+ return $z > 0 ? CORE::log($z) : cplx(CORE::log(-$z), pi);
908
+ }
909
+ my ($r, $t) = @{$z->_polar};
910
+ _logofzero("log") if $r == 0;
911
+ if ($t > pi()) { $t -= pi2 }
912
+ elsif ($t <= -pi()) { $t += pi2 }
913
+ return (ref $z)->make(CORE::log($r), $t);
914
+ }
915
+
916
+ #
917
+ # ln
918
+ #
919
+ # Alias for log().
920
+ #
921
+ sub ln { Math::Complex::log(@_) }
922
+
923
+ #
924
+ # log10
925
+ #
926
+ # Compute log10(z).
927
+ #
928
+
929
+ sub log10 {
930
+ return Math::Complex::log($_[0]) * _uplog10;
931
+ }
932
+
933
+ #
934
+ # logn
935
+ #
936
+ # Compute logn(z,n) = log(z) / log(n)
937
+ #
938
+ sub logn {
939
+ my ($z, $n) = @_;
940
+ $z = cplx($z, 0) unless ref $z;
941
+ my $logn = $LOGN{$n};
942
+ $logn = $LOGN{$n} = CORE::log($n) unless defined $logn; # Cache log(n)
943
+ return &log($z) / $logn;
944
+ }
945
+
946
+ #
947
+ # (cos)
948
+ #
949
+ # Compute cos(z) = (exp(iz) + exp(-iz))/2.
950
+ #
951
+ sub cos {
952
+ my ($z) = @_ ? @_ : $_;
953
+ return CORE::cos($z) unless ref $z;
954
+ my ($x, $y) = @{$z->_cartesian};
955
+ my $ey = CORE::exp($y);
956
+ my $sx = CORE::sin($x);
957
+ my $cx = CORE::cos($x);
958
+ my $ey_1 = $ey ? 1 / $ey : Inf();
959
+ return (ref $z)->make($cx * ($ey + $ey_1)/2,
960
+ $sx * ($ey_1 - $ey)/2);
961
+ }
962
+
963
+ #
964
+ # (sin)
965
+ #
966
+ # Compute sin(z) = (exp(iz) - exp(-iz))/2.
967
+ #
968
+ sub sin {
969
+ my ($z) = @_ ? @_ : $_;
970
+ return CORE::sin($z) unless ref $z;
971
+ my ($x, $y) = @{$z->_cartesian};
972
+ my $ey = CORE::exp($y);
973
+ my $sx = CORE::sin($x);
974
+ my $cx = CORE::cos($x);
975
+ my $ey_1 = $ey ? 1 / $ey : Inf();
976
+ return (ref $z)->make($sx * ($ey + $ey_1)/2,
977
+ $cx * ($ey - $ey_1)/2);
978
+ }
979
+
980
+ #
981
+ # tan
982
+ #
983
+ # Compute tan(z) = sin(z) / cos(z).
984
+ #
985
+ sub tan {
986
+ my ($z) = @_;
987
+ my $cz = &cos($z);
988
+ _divbyzero "tan($z)", "cos($z)" if $cz == 0;
989
+ return &sin($z) / $cz;
990
+ }
991
+
992
+ #
993
+ # sec
994
+ #
995
+ # Computes the secant sec(z) = 1 / cos(z).
996
+ #
997
+ sub sec {
998
+ my ($z) = @_;
999
+ my $cz = &cos($z);
1000
+ _divbyzero "sec($z)", "cos($z)" if ($cz == 0);
1001
+ return 1 / $cz;
1002
+ }
1003
+
1004
+ #
1005
+ # csc
1006
+ #
1007
+ # Computes the cosecant csc(z) = 1 / sin(z).
1008
+ #
1009
+ sub csc {
1010
+ my ($z) = @_;
1011
+ my $sz = &sin($z);
1012
+ _divbyzero "csc($z)", "sin($z)" if ($sz == 0);
1013
+ return 1 / $sz;
1014
+ }
1015
+
1016
+ #
1017
+ # cosec
1018
+ #
1019
+ # Alias for csc().
1020
+ #
1021
+ sub cosec { Math::Complex::csc(@_) }
1022
+
1023
+ #
1024
+ # cot
1025
+ #
1026
+ # Computes cot(z) = cos(z) / sin(z).
1027
+ #
1028
+ sub cot {
1029
+ my ($z) = @_;
1030
+ my $sz = &sin($z);
1031
+ _divbyzero "cot($z)", "sin($z)" if ($sz == 0);
1032
+ return &cos($z) / $sz;
1033
+ }
1034
+
1035
+ #
1036
+ # cotan
1037
+ #
1038
+ # Alias for cot().
1039
+ #
1040
+ sub cotan { Math::Complex::cot(@_) }
1041
+
1042
+ #
1043
+ # acos
1044
+ #
1045
+ # Computes the arc cosine acos(z) = -i log(z + sqrt(z*z-1)).
1046
+ #
1047
+ sub acos {
1048
+ my $z = $_[0];
1049
+ return CORE::atan2(CORE::sqrt(1-$z*$z), $z)
1050
+ if (! ref $z) && CORE::abs($z) <= 1;
1051
+ $z = cplx($z, 0) unless ref $z;
1052
+ my ($x, $y) = @{$z->_cartesian};
1053
+ return 0 if $x == 1 && $y == 0;
1054
+ my $t1 = CORE::sqrt(($x+1)*($x+1) + $y*$y);
1055
+ my $t2 = CORE::sqrt(($x-1)*($x-1) + $y*$y);
1056
+ my $alpha = ($t1 + $t2)/2;
1057
+ my $beta = ($t1 - $t2)/2;
1058
+ $alpha = 1 if $alpha < 1;
1059
+ if ($beta > 1) { $beta = 1 }
1060
+ elsif ($beta < -1) { $beta = -1 }
1061
+ my $u = CORE::atan2(CORE::sqrt(1-$beta*$beta), $beta);
1062
+ my $v = CORE::log($alpha + CORE::sqrt($alpha*$alpha-1));
1063
+ $v = -$v if $y > 0 || ($y == 0 && $x < -1);
1064
+ return (ref $z)->make($u, $v);
1065
+ }
1066
+
1067
+ #
1068
+ # asin
1069
+ #
1070
+ # Computes the arc sine asin(z) = -i log(iz + sqrt(1-z*z)).
1071
+ #
1072
+ sub asin {
1073
+ my $z = $_[0];
1074
+ return CORE::atan2($z, CORE::sqrt(1-$z*$z))
1075
+ if (! ref $z) && CORE::abs($z) <= 1;
1076
+ $z = cplx($z, 0) unless ref $z;
1077
+ my ($x, $y) = @{$z->_cartesian};
1078
+ return 0 if $x == 0 && $y == 0;
1079
+ my $t1 = CORE::sqrt(($x+1)*($x+1) + $y*$y);
1080
+ my $t2 = CORE::sqrt(($x-1)*($x-1) + $y*$y);
1081
+ my $alpha = ($t1 + $t2)/2;
1082
+ my $beta = ($t1 - $t2)/2;
1083
+ $alpha = 1 if $alpha < 1;
1084
+ if ($beta > 1) { $beta = 1 }
1085
+ elsif ($beta < -1) { $beta = -1 }
1086
+ my $u = CORE::atan2($beta, CORE::sqrt(1-$beta*$beta));
1087
+ my $v = -CORE::log($alpha + CORE::sqrt($alpha*$alpha-1));
1088
+ $v = -$v if $y > 0 || ($y == 0 && $x < -1);
1089
+ return (ref $z)->make($u, $v);
1090
+ }
1091
+
1092
+ #
1093
+ # atan
1094
+ #
1095
+ # Computes the arc tangent atan(z) = i/2 log((i+z) / (i-z)).
1096
+ #
1097
+ sub atan {
1098
+ my ($z) = @_;
1099
+ return CORE::atan2($z, 1) unless ref $z;
1100
+ my ($x, $y) = ref $z ? @{$z->_cartesian} : ($z, 0);
1101
+ return 0 if $x == 0 && $y == 0;
1102
+ _divbyzero "atan(i)" if ( $z == i);
1103
+ _logofzero "atan(-i)" if (-$z == i); # -i is a bad file test...
1104
+ my $log = &log((i + $z) / (i - $z));
1105
+ return _ip2 * $log;
1106
+ }
1107
+
1108
+ #
1109
+ # asec
1110
+ #
1111
+ # Computes the arc secant asec(z) = acos(1 / z).
1112
+ #
1113
+ sub asec {
1114
+ my ($z) = @_;
1115
+ _divbyzero "asec($z)", $z if ($z == 0);
1116
+ return acos(1 / $z);
1117
+ }
1118
+
1119
+ #
1120
+ # acsc
1121
+ #
1122
+ # Computes the arc cosecant acsc(z) = asin(1 / z).
1123
+ #
1124
+ sub acsc {
1125
+ my ($z) = @_;
1126
+ _divbyzero "acsc($z)", $z if ($z == 0);
1127
+ return asin(1 / $z);
1128
+ }
1129
+
1130
+ #
1131
+ # acosec
1132
+ #
1133
+ # Alias for acsc().
1134
+ #
1135
+ sub acosec { Math::Complex::acsc(@_) }
1136
+
1137
+ #
1138
+ # acot
1139
+ #
1140
+ # Computes the arc cotangent acot(z) = atan(1 / z)
1141
+ #
1142
+ sub acot {
1143
+ my ($z) = @_;
1144
+ _divbyzero "acot(0)" if $z == 0;
1145
+ return ($z >= 0) ? CORE::atan2(1, $z) : CORE::atan2(-1, -$z)
1146
+ unless ref $z;
1147
+ _divbyzero "acot(i)" if ($z - i == 0);
1148
+ _logofzero "acot(-i)" if ($z + i == 0);
1149
+ return atan(1 / $z);
1150
+ }
1151
+
1152
+ #
1153
+ # acotan
1154
+ #
1155
+ # Alias for acot().
1156
+ #
1157
+ sub acotan { Math::Complex::acot(@_) }
1158
+
1159
+ #
1160
+ # cosh
1161
+ #
1162
+ # Computes the hyperbolic cosine cosh(z) = (exp(z) + exp(-z))/2.
1163
+ #
1164
+ sub cosh {
1165
+ my ($z) = @_;
1166
+ my $ex;
1167
+ unless (ref $z) {
1168
+ $ex = CORE::exp($z);
1169
+ return $ex ? ($ex == $ExpInf ? Inf() : ($ex + 1/$ex)/2) : Inf();
1170
+ }
1171
+ my ($x, $y) = @{$z->_cartesian};
1172
+ $ex = CORE::exp($x);
1173
+ my $ex_1 = $ex ? 1 / $ex : Inf();
1174
+ return (ref $z)->make(CORE::cos($y) * ($ex + $ex_1)/2,
1175
+ CORE::sin($y) * ($ex - $ex_1)/2);
1176
+ }
1177
+
1178
+ #
1179
+ # sinh
1180
+ #
1181
+ # Computes the hyperbolic sine sinh(z) = (exp(z) - exp(-z))/2.
1182
+ #
1183
+ sub sinh {
1184
+ my ($z) = @_;
1185
+ my $ex;
1186
+ unless (ref $z) {
1187
+ return 0 if $z == 0;
1188
+ $ex = CORE::exp($z);
1189
+ return $ex ? ($ex == $ExpInf ? Inf() : ($ex - 1/$ex)/2) : -Inf();
1190
+ }
1191
+ my ($x, $y) = @{$z->_cartesian};
1192
+ my $cy = CORE::cos($y);
1193
+ my $sy = CORE::sin($y);
1194
+ $ex = CORE::exp($x);
1195
+ my $ex_1 = $ex ? 1 / $ex : Inf();
1196
+ return (ref $z)->make(CORE::cos($y) * ($ex - $ex_1)/2,
1197
+ CORE::sin($y) * ($ex + $ex_1)/2);
1198
+ }
1199
+
1200
+ #
1201
+ # tanh
1202
+ #
1203
+ # Computes the hyperbolic tangent tanh(z) = sinh(z) / cosh(z).
1204
+ #
1205
+ sub tanh {
1206
+ my ($z) = @_;
1207
+ my $cz = cosh($z);
1208
+ _divbyzero "tanh($z)", "cosh($z)" if ($cz == 0);
1209
+ my $sz = sinh($z);
1210
+ return 1 if $cz == $sz;
1211
+ return -1 if $cz == -$sz;
1212
+ return $sz / $cz;
1213
+ }
1214
+
1215
+ #
1216
+ # sech
1217
+ #
1218
+ # Computes the hyperbolic secant sech(z) = 1 / cosh(z).
1219
+ #
1220
+ sub sech {
1221
+ my ($z) = @_;
1222
+ my $cz = cosh($z);
1223
+ _divbyzero "sech($z)", "cosh($z)" if ($cz == 0);
1224
+ return 1 / $cz;
1225
+ }
1226
+
1227
+ #
1228
+ # csch
1229
+ #
1230
+ # Computes the hyperbolic cosecant csch(z) = 1 / sinh(z).
1231
+ #
1232
+ sub csch {
1233
+ my ($z) = @_;
1234
+ my $sz = sinh($z);
1235
+ _divbyzero "csch($z)", "sinh($z)" if ($sz == 0);
1236
+ return 1 / $sz;
1237
+ }
1238
+
1239
+ #
1240
+ # cosech
1241
+ #
1242
+ # Alias for csch().
1243
+ #
1244
+ sub cosech { Math::Complex::csch(@_) }
1245
+
1246
+ #
1247
+ # coth
1248
+ #
1249
+ # Computes the hyperbolic cotangent coth(z) = cosh(z) / sinh(z).
1250
+ #
1251
+ sub coth {
1252
+ my ($z) = @_;
1253
+ my $sz = sinh($z);
1254
+ _divbyzero "coth($z)", "sinh($z)" if $sz == 0;
1255
+ my $cz = cosh($z);
1256
+ return 1 if $cz == $sz;
1257
+ return -1 if $cz == -$sz;
1258
+ return $cz / $sz;
1259
+ }
1260
+
1261
+ #
1262
+ # cotanh
1263
+ #
1264
+ # Alias for coth().
1265
+ #
1266
+ sub cotanh { Math::Complex::coth(@_) }
1267
+
1268
+ #
1269
+ # acosh
1270
+ #
1271
+ # Computes the area/inverse hyperbolic cosine acosh(z) = log(z + sqrt(z*z-1)).
1272
+ #
1273
+ sub acosh {
1274
+ my ($z) = @_;
1275
+ unless (ref $z) {
1276
+ $z = cplx($z, 0);
1277
+ }
1278
+ my ($re, $im) = @{$z->_cartesian};
1279
+ if ($im == 0) {
1280
+ return CORE::log($re + CORE::sqrt($re*$re - 1))
1281
+ if $re >= 1;
1282
+ return cplx(0, CORE::atan2(CORE::sqrt(1 - $re*$re), $re))
1283
+ if CORE::abs($re) < 1;
1284
+ }
1285
+ my $t = &sqrt($z * $z - 1) + $z;
1286
+ # Try Taylor if looking bad (this usually means that
1287
+ # $z was large negative, therefore the sqrt is really
1288
+ # close to abs(z), summing that with z...)
1289
+ $t = 1/(2 * $z) - 1/(8 * $z**3) + 1/(16 * $z**5) - 5/(128 * $z**7)
1290
+ if $t == 0;
1291
+ my $u = &log($t);
1292
+ $u->Im(-$u->Im) if $re < 0 && $im == 0;
1293
+ return $re < 0 ? -$u : $u;
1294
+ }
1295
+
1296
+ #
1297
+ # asinh
1298
+ #
1299
+ # Computes the area/inverse hyperbolic sine asinh(z) = log(z + sqrt(z*z+1))
1300
+ #
1301
+ sub asinh {
1302
+ my ($z) = @_;
1303
+ unless (ref $z) {
1304
+ my $t = $z + CORE::sqrt($z*$z + 1);
1305
+ return CORE::log($t) if $t;
1306
+ }
1307
+ my $t = &sqrt($z * $z + 1) + $z;
1308
+ # Try Taylor if looking bad (this usually means that
1309
+ # $z was large negative, therefore the sqrt is really
1310
+ # close to abs(z), summing that with z...)
1311
+ $t = 1/(2 * $z) - 1/(8 * $z**3) + 1/(16 * $z**5) - 5/(128 * $z**7)
1312
+ if $t == 0;
1313
+ return &log($t);
1314
+ }
1315
+
1316
+ #
1317
+ # atanh
1318
+ #
1319
+ # Computes the area/inverse hyperbolic tangent atanh(z) = 1/2 log((1+z) / (1-z)).
1320
+ #
1321
+ sub atanh {
1322
+ my ($z) = @_;
1323
+ unless (ref $z) {
1324
+ return CORE::log((1 + $z)/(1 - $z))/2 if CORE::abs($z) < 1;
1325
+ $z = cplx($z, 0);
1326
+ }
1327
+ _divbyzero 'atanh(1)', "1 - $z" if (1 - $z == 0);
1328
+ _logofzero 'atanh(-1)' if (1 + $z == 0);
1329
+ return 0.5 * &log((1 + $z) / (1 - $z));
1330
+ }
1331
+
1332
+ #
1333
+ # asech
1334
+ #
1335
+ # Computes the area/inverse hyperbolic secant asech(z) = acosh(1 / z).
1336
+ #
1337
+ sub asech {
1338
+ my ($z) = @_;
1339
+ _divbyzero 'asech(0)', "$z" if ($z == 0);
1340
+ return acosh(1 / $z);
1341
+ }
1342
+
1343
+ #
1344
+ # acsch
1345
+ #
1346
+ # Computes the area/inverse hyperbolic cosecant acsch(z) = asinh(1 / z).
1347
+ #
1348
+ sub acsch {
1349
+ my ($z) = @_;
1350
+ _divbyzero 'acsch(0)', $z if ($z == 0);
1351
+ return asinh(1 / $z);
1352
+ }
1353
+
1354
+ #
1355
+ # acosech
1356
+ #
1357
+ # Alias for acosh().
1358
+ #
1359
+ sub acosech { Math::Complex::acsch(@_) }
1360
+
1361
+ #
1362
+ # acoth
1363
+ #
1364
+ # Computes the area/inverse hyperbolic cotangent acoth(z) = 1/2 log((1+z) / (z-1)).
1365
+ #
1366
+ sub acoth {
1367
+ my ($z) = @_;
1368
+ _divbyzero 'acoth(0)' if ($z == 0);
1369
+ unless (ref $z) {
1370
+ return CORE::log(($z + 1)/($z - 1))/2 if CORE::abs($z) > 1;
1371
+ $z = cplx($z, 0);
1372
+ }
1373
+ _divbyzero 'acoth(1)', "$z - 1" if ($z - 1 == 0);
1374
+ _logofzero 'acoth(-1)', "1 + $z" if (1 + $z == 0);
1375
+ return &log((1 + $z) / ($z - 1)) / 2;
1376
+ }
1377
+
1378
+ #
1379
+ # acotanh
1380
+ #
1381
+ # Alias for acot().
1382
+ #
1383
+ sub acotanh { Math::Complex::acoth(@_) }
1384
+
1385
+ #
1386
+ # (atan2)
1387
+ #
1388
+ # Compute atan(z1/z2), minding the right quadrant.
1389
+ #
1390
+ sub atan2 {
1391
+ my ($z1, $z2, $inverted) = @_;
1392
+ my ($re1, $im1, $re2, $im2);
1393
+ if ($inverted) {
1394
+ ($re1, $im1) = ref $z2 ? @{$z2->_cartesian} : ($z2, 0);
1395
+ ($re2, $im2) = ref $z1 ? @{$z1->_cartesian} : ($z1, 0);
1396
+ } else {
1397
+ ($re1, $im1) = ref $z1 ? @{$z1->_cartesian} : ($z1, 0);
1398
+ ($re2, $im2) = ref $z2 ? @{$z2->_cartesian} : ($z2, 0);
1399
+ }
1400
+ if ($im1 || $im2) {
1401
+ # In MATLAB the imaginary parts are ignored.
1402
+ # warn "atan2: Imaginary parts ignored";
1403
+ # http://documents.wolfram.com/mathematica/functions/ArcTan
1404
+ # NOTE: Mathematica ArcTan[x,y] while atan2(y,x)
1405
+ my $s = $z1 * $z1 + $z2 * $z2;
1406
+ _divbyzero("atan2") if $s == 0;
1407
+ my $i = &i;
1408
+ my $r = $z2 + $z1 * $i;
1409
+ return -$i * &log($r / &sqrt( $s ));
1410
+ }
1411
+ return CORE::atan2($re1, $re2);
1412
+ }
1413
+
1414
+ #
1415
+ # display_format
1416
+ # ->display_format
1417
+ #
1418
+ # Set (get if no argument) the display format for all complex numbers that
1419
+ # don't happen to have overridden it via ->display_format
1420
+ #
1421
+ # When called as an object method, this actually sets the display format for
1422
+ # the current object.
1423
+ #
1424
+ # Valid object formats are 'c' and 'p' for cartesian and polar. The first
1425
+ # letter is used actually, so the type can be fully spelled out for clarity.
1426
+ #
1427
+ sub display_format {
1428
+ my $self = shift;
1429
+ my %display_format = %DISPLAY_FORMAT;
1430
+
1431
+ if (ref $self) { # Called as an object method
1432
+ if (exists $self->{display_format}) {
1433
+ my %obj = %{$self->{display_format}};
1434
+ @display_format{keys %obj} = values %obj;
1435
+ }
1436
+ }
1437
+ if (@_ == 1) {
1438
+ $display_format{style} = shift;
1439
+ } else {
1440
+ my %new = @_;
1441
+ @display_format{keys %new} = values %new;
1442
+ }
1443
+
1444
+ if (ref $self) { # Called as an object method
1445
+ $self->{display_format} = { %display_format };
1446
+ return
1447
+ wantarray ?
1448
+ %{$self->{display_format}} :
1449
+ $self->{display_format}->{style};
1450
+ }
1451
+
1452
+ # Called as a class method
1453
+ %DISPLAY_FORMAT = %display_format;
1454
+ return
1455
+ wantarray ?
1456
+ %DISPLAY_FORMAT :
1457
+ $DISPLAY_FORMAT{style};
1458
+ }
1459
+
1460
+ #
1461
+ # (_stringify)
1462
+ #
1463
+ # Show nicely formatted complex number under its cartesian or polar form,
1464
+ # depending on the current display format:
1465
+ #
1466
+ # . If a specific display format has been recorded for this object, use it.
1467
+ # . Otherwise, use the generic current default for all complex numbers,
1468
+ # which is a package global variable.
1469
+ #
1470
+ sub _stringify {
1471
+ my ($z) = shift;
1472
+
1473
+ my $style = $z->display_format;
1474
+
1475
+ $style = $DISPLAY_FORMAT{style} unless defined $style;
1476
+
1477
+ return $z->_stringify_polar if $style =~ /^p/i;
1478
+ return $z->_stringify_cartesian;
1479
+ }
1480
+
1481
+ #
1482
+ # ->_stringify_cartesian
1483
+ #
1484
+ # Stringify as a cartesian representation 'a+bi'.
1485
+ #
1486
+ sub _stringify_cartesian {
1487
+ my $z = shift;
1488
+ my ($x, $y) = @{$z->_cartesian};
1489
+ my ($re, $im);
1490
+
1491
+ my %format = $z->display_format;
1492
+ my $format = $format{format};
1493
+
1494
+ if ($x) {
1495
+ if ($x =~ /^NaN[QS]?$/i) {
1496
+ $re = $x;
1497
+ } else {
1498
+ if ($x =~ /^-?\Q$Inf\E$/oi) {
1499
+ $re = $x;
1500
+ } else {
1501
+ $re = defined $format ? sprintf($format, $x) : $x;
1502
+ }
1503
+ }
1504
+ } else {
1505
+ undef $re;
1506
+ }
1507
+
1508
+ if ($y) {
1509
+ if ($y =~ /^(NaN[QS]?)$/i) {
1510
+ $im = $y;
1511
+ } else {
1512
+ if ($y =~ /^-?\Q$Inf\E$/oi) {
1513
+ $im = $y;
1514
+ } else {
1515
+ $im =
1516
+ defined $format ?
1517
+ sprintf($format, $y) :
1518
+ ($y == 1 ? "" : ($y == -1 ? "-" : $y));
1519
+ }
1520
+ }
1521
+ $im .= "i";
1522
+ } else {
1523
+ undef $im;
1524
+ }
1525
+
1526
+ my $str = $re;
1527
+
1528
+ if (defined $im) {
1529
+ if ($y < 0) {
1530
+ $str .= $im;
1531
+ } elsif ($y > 0 || $im =~ /^NaN[QS]?i$/i) {
1532
+ $str .= "+" if defined $re;
1533
+ $str .= $im;
1534
+ }
1535
+ } elsif (!defined $re) {
1536
+ $str = "0";
1537
+ }
1538
+
1539
+ return $str;
1540
+ }
1541
+
1542
+
1543
+ #
1544
+ # ->_stringify_polar
1545
+ #
1546
+ # Stringify as a polar representation '[r,t]'.
1547
+ #
1548
+ sub _stringify_polar {
1549
+ my $z = shift;
1550
+ my ($r, $t) = @{$z->_polar};
1551
+ my $theta;
1552
+
1553
+ my %format = $z->display_format;
1554
+ my $format = $format{format};
1555
+
1556
+ if ($t =~ /^NaN[QS]?$/i || $t =~ /^-?\Q$Inf\E$/oi) {
1557
+ $theta = $t;
1558
+ } elsif ($t == pi) {
1559
+ $theta = "pi";
1560
+ } elsif ($r == 0 || $t == 0) {
1561
+ $theta = defined $format ? sprintf($format, $t) : $t;
1562
+ }
1563
+
1564
+ return "[$r,$theta]" if defined $theta;
1565
+
1566
+ #
1567
+ # Try to identify pi/n and friends.
1568
+ #
1569
+
1570
+ $t -= int(CORE::abs($t) / pi2) * pi2;
1571
+
1572
+ if ($format{polar_pretty_print} && $t) {
1573
+ my ($a, $b);
1574
+ for $a (2..9) {
1575
+ $b = $t * $a / pi;
1576
+ if ($b =~ /^-?\d+$/) {
1577
+ $b = $b < 0 ? "-" : "" if CORE::abs($b) == 1;
1578
+ $theta = "${b}pi/$a";
1579
+ last;
1580
+ }
1581
+ }
1582
+ }
1583
+
1584
+ if (defined $format) {
1585
+ $r = sprintf($format, $r);
1586
+ $theta = sprintf($format, $t) unless defined $theta;
1587
+ } else {
1588
+ $theta = $t unless defined $theta;
1589
+ }
1590
+
1591
+ return "[$r,$theta]";
1592
+ }
1593
+
1594
+ sub Inf {
1595
+ return $Inf;
1596
+ }
1597
+
1598
+ 1;
1599
+ __END__
1600
+
1601
+ =pod
1602
+
1603
+ =head1 NAME
1604
+
1605
+ Math::Complex - complex numbers and associated mathematical functions
1606
+
1607
+ =head1 SYNOPSIS
1608
+
1609
+ use Math::Complex;
1610
+
1611
+ $z = Math::Complex->make(5, 6);
1612
+ $t = 4 - 3*i + $z;
1613
+ $j = cplxe(1, 2*pi/3);
1614
+
1615
+ =head1 DESCRIPTION
1616
+
1617
+ This package lets you create and manipulate complex numbers. By default,
1618
+ I<Perl> limits itself to real numbers, but an extra C<use> statement brings
1619
+ full complex support, along with a full set of mathematical functions
1620
+ typically associated with and/or extended to complex numbers.
1621
+
1622
+ If you wonder what complex numbers are, they were invented to be able to solve
1623
+ the following equation:
1624
+
1625
+ x*x = -1
1626
+
1627
+ and by definition, the solution is noted I<i> (engineers use I<j> instead since
1628
+ I<i> usually denotes an intensity, but the name does not matter). The number
1629
+ I<i> is a pure I<imaginary> number.
1630
+
1631
+ The arithmetics with pure imaginary numbers works just like you would expect
1632
+ it with real numbers... you just have to remember that
1633
+
1634
+ i*i = -1
1635
+
1636
+ so you have:
1637
+
1638
+ 5i + 7i = i * (5 + 7) = 12i
1639
+ 4i - 3i = i * (4 - 3) = i
1640
+ 4i * 2i = -8
1641
+ 6i / 2i = 3
1642
+ 1 / i = -i
1643
+
1644
+ Complex numbers are numbers that have both a real part and an imaginary
1645
+ part, and are usually noted:
1646
+
1647
+ a + bi
1648
+
1649
+ where C<a> is the I<real> part and C<b> is the I<imaginary> part. The
1650
+ arithmetic with complex numbers is straightforward. You have to
1651
+ keep track of the real and the imaginary parts, but otherwise the
1652
+ rules used for real numbers just apply:
1653
+
1654
+ (4 + 3i) + (5 - 2i) = (4 + 5) + i(3 - 2) = 9 + i
1655
+ (2 + i) * (4 - i) = 2*4 + 4i -2i -i*i = 8 + 2i + 1 = 9 + 2i
1656
+
1657
+ A graphical representation of complex numbers is possible in a plane
1658
+ (also called the I<complex plane>, but it's really a 2D plane).
1659
+ The number
1660
+
1661
+ z = a + bi
1662
+
1663
+ is the point whose coordinates are (a, b). Actually, it would
1664
+ be the vector originating from (0, 0) to (a, b). It follows that the addition
1665
+ of two complex numbers is a vectorial addition.
1666
+
1667
+ Since there is a bijection between a point in the 2D plane and a complex
1668
+ number (i.e. the mapping is unique and reciprocal), a complex number
1669
+ can also be uniquely identified with polar coordinates:
1670
+
1671
+ [rho, theta]
1672
+
1673
+ where C<rho> is the distance to the origin, and C<theta> the angle between
1674
+ the vector and the I<x> axis. There is a notation for this using the
1675
+ exponential form, which is:
1676
+
1677
+ rho * exp(i * theta)
1678
+
1679
+ where I<i> is the famous imaginary number introduced above. Conversion
1680
+ between this form and the cartesian form C<a + bi> is immediate:
1681
+
1682
+ a = rho * cos(theta)
1683
+ b = rho * sin(theta)
1684
+
1685
+ which is also expressed by this formula:
1686
+
1687
+ z = rho * exp(i * theta) = rho * (cos theta + i * sin theta)
1688
+
1689
+ In other words, it's the projection of the vector onto the I<x> and I<y>
1690
+ axes. Mathematicians call I<rho> the I<norm> or I<modulus> and I<theta>
1691
+ the I<argument> of the complex number. The I<norm> of C<z> is
1692
+ marked here as C<abs(z)>.
1693
+
1694
+ The polar notation (also known as the trigonometric representation) is
1695
+ much more handy for performing multiplications and divisions of
1696
+ complex numbers, whilst the cartesian notation is better suited for
1697
+ additions and subtractions. Real numbers are on the I<x> axis, and
1698
+ therefore I<y> or I<theta> is zero or I<pi>.
1699
+
1700
+ All the common operations that can be performed on a real number have
1701
+ been defined to work on complex numbers as well, and are merely
1702
+ I<extensions> of the operations defined on real numbers. This means
1703
+ they keep their natural meaning when there is no imaginary part, provided
1704
+ the number is within their definition set.
1705
+
1706
+ For instance, the C<sqrt> routine which computes the square root of
1707
+ its argument is only defined for non-negative real numbers and yields a
1708
+ non-negative real number (it is an application from B<R+> to B<R+>).
1709
+ If we allow it to return a complex number, then it can be extended to
1710
+ negative real numbers to become an application from B<R> to B<C> (the
1711
+ set of complex numbers):
1712
+
1713
+ sqrt(x) = x >= 0 ? sqrt(x) : sqrt(-x)*i
1714
+
1715
+ It can also be extended to be an application from B<C> to B<C>,
1716
+ whilst its restriction to B<R> behaves as defined above by using
1717
+ the following definition:
1718
+
1719
+ sqrt(z = [r,t]) = sqrt(r) * exp(i * t/2)
1720
+
1721
+ Indeed, a negative real number can be noted C<[x,pi]> (the modulus
1722
+ I<x> is always non-negative, so C<[x,pi]> is really C<-x>, a negative
1723
+ number) and the above definition states that
1724
+
1725
+ sqrt([x,pi]) = sqrt(x) * exp(i*pi/2) = [sqrt(x),pi/2] = sqrt(x)*i
1726
+
1727
+ which is exactly what we had defined for negative real numbers above.
1728
+ The C<sqrt> returns only one of the solutions: if you want the both,
1729
+ use the C<root> function.
1730
+
1731
+ All the common mathematical functions defined on real numbers that
1732
+ are extended to complex numbers share that same property of working
1733
+ I<as usual> when the imaginary part is zero (otherwise, it would not
1734
+ be called an extension, would it?).
1735
+
1736
+ A I<new> operation possible on a complex number that is
1737
+ the identity for real numbers is called the I<conjugate>, and is noted
1738
+ with a horizontal bar above the number, or C<~z> here.
1739
+
1740
+ z = a + bi
1741
+ ~z = a - bi
1742
+
1743
+ Simple... Now look:
1744
+
1745
+ z * ~z = (a + bi) * (a - bi) = a*a + b*b
1746
+
1747
+ We saw that the norm of C<z> was noted C<abs(z)> and was defined as the
1748
+ distance to the origin, also known as:
1749
+
1750
+ rho = abs(z) = sqrt(a*a + b*b)
1751
+
1752
+ so
1753
+
1754
+ z * ~z = abs(z) ** 2
1755
+
1756
+ If z is a pure real number (i.e. C<b == 0>), then the above yields:
1757
+
1758
+ a * a = abs(a) ** 2
1759
+
1760
+ which is true (C<abs> has the regular meaning for real number, i.e. stands
1761
+ for the absolute value). This example explains why the norm of C<z> is
1762
+ noted C<abs(z)>: it extends the C<abs> function to complex numbers, yet
1763
+ is the regular C<abs> we know when the complex number actually has no
1764
+ imaginary part... This justifies I<a posteriori> our use of the C<abs>
1765
+ notation for the norm.
1766
+
1767
+ =head1 OPERATIONS
1768
+
1769
+ Given the following notations:
1770
+
1771
+ z1 = a + bi = r1 * exp(i * t1)
1772
+ z2 = c + di = r2 * exp(i * t2)
1773
+ z = <any complex or real number>
1774
+
1775
+ the following (overloaded) operations are supported on complex numbers:
1776
+
1777
+ z1 + z2 = (a + c) + i(b + d)
1778
+ z1 - z2 = (a - c) + i(b - d)
1779
+ z1 * z2 = (r1 * r2) * exp(i * (t1 + t2))
1780
+ z1 / z2 = (r1 / r2) * exp(i * (t1 - t2))
1781
+ z1 ** z2 = exp(z2 * log z1)
1782
+ ~z = a - bi
1783
+ abs(z) = r1 = sqrt(a*a + b*b)
1784
+ sqrt(z) = sqrt(r1) * exp(i * t/2)
1785
+ exp(z) = exp(a) * exp(i * b)
1786
+ log(z) = log(r1) + i*t
1787
+ sin(z) = 1/2i (exp(i * z1) - exp(-i * z))
1788
+ cos(z) = 1/2 (exp(i * z1) + exp(-i * z))
1789
+ atan2(y, x) = atan(y / x) # Minding the right quadrant, note the order.
1790
+
1791
+ The definition used for complex arguments of atan2() is
1792
+
1793
+ -i log((x + iy)/sqrt(x*x+y*y))
1794
+
1795
+ Note that atan2(0, 0) is not well-defined.
1796
+
1797
+ The following extra operations are supported on both real and complex
1798
+ numbers:
1799
+
1800
+ Re(z) = a
1801
+ Im(z) = b
1802
+ arg(z) = t
1803
+ abs(z) = r
1804
+
1805
+ cbrt(z) = z ** (1/3)
1806
+ log10(z) = log(z) / log(10)
1807
+ logn(z, n) = log(z) / log(n)
1808
+
1809
+ tan(z) = sin(z) / cos(z)
1810
+
1811
+ csc(z) = 1 / sin(z)
1812
+ sec(z) = 1 / cos(z)
1813
+ cot(z) = 1 / tan(z)
1814
+
1815
+ asin(z) = -i * log(i*z + sqrt(1-z*z))
1816
+ acos(z) = -i * log(z + i*sqrt(1-z*z))
1817
+ atan(z) = i/2 * log((i+z) / (i-z))
1818
+
1819
+ acsc(z) = asin(1 / z)
1820
+ asec(z) = acos(1 / z)
1821
+ acot(z) = atan(1 / z) = -i/2 * log((i+z) / (z-i))
1822
+
1823
+ sinh(z) = 1/2 (exp(z) - exp(-z))
1824
+ cosh(z) = 1/2 (exp(z) + exp(-z))
1825
+ tanh(z) = sinh(z) / cosh(z) = (exp(z) - exp(-z)) / (exp(z) + exp(-z))
1826
+
1827
+ csch(z) = 1 / sinh(z)
1828
+ sech(z) = 1 / cosh(z)
1829
+ coth(z) = 1 / tanh(z)
1830
+
1831
+ asinh(z) = log(z + sqrt(z*z+1))
1832
+ acosh(z) = log(z + sqrt(z*z-1))
1833
+ atanh(z) = 1/2 * log((1+z) / (1-z))
1834
+
1835
+ acsch(z) = asinh(1 / z)
1836
+ asech(z) = acosh(1 / z)
1837
+ acoth(z) = atanh(1 / z) = 1/2 * log((1+z) / (z-1))
1838
+
1839
+ I<arg>, I<abs>, I<log>, I<csc>, I<cot>, I<acsc>, I<acot>, I<csch>,
1840
+ I<coth>, I<acosech>, I<acotanh>, have aliases I<rho>, I<theta>, I<ln>,
1841
+ I<cosec>, I<cotan>, I<acosec>, I<acotan>, I<cosech>, I<cotanh>,
1842
+ I<acosech>, I<acotanh>, respectively. C<Re>, C<Im>, C<arg>, C<abs>,
1843
+ C<rho>, and C<theta> can be used also as mutators. The C<cbrt>
1844
+ returns only one of the solutions: if you want all three, use the
1845
+ C<root> function.
1846
+
1847
+ The I<root> function is available to compute all the I<n>
1848
+ roots of some complex, where I<n> is a strictly positive integer.
1849
+ There are exactly I<n> such roots, returned as a list. Getting the
1850
+ number mathematicians call C<j> such that:
1851
+
1852
+ 1 + j + j*j = 0;
1853
+
1854
+ is a simple matter of writing:
1855
+
1856
+ $j = (root(1, 3))[1];
1857
+
1858
+ The I<k>th root for C<z = [r,t]> is given by:
1859
+
1860
+ (root(z, n))[k] = r**(1/n) * exp(i * (t + 2*k*pi)/n)
1861
+
1862
+ You can return the I<k>th root directly by C<root(z, n, k)>,
1863
+ indexing starting from I<zero> and ending at I<n - 1>.
1864
+
1865
+ The I<spaceship> numeric comparison operator, E<lt>=E<gt>, is also
1866
+ defined. In order to ensure its restriction to real numbers is conform
1867
+ to what you would expect, the comparison is run on the real part of
1868
+ the complex number first, and imaginary parts are compared only when
1869
+ the real parts match.
1870
+
1871
+ =head1 CREATION
1872
+
1873
+ To create a complex number, use either:
1874
+
1875
+ $z = Math::Complex->make(3, 4);
1876
+ $z = cplx(3, 4);
1877
+
1878
+ if you know the cartesian form of the number, or
1879
+
1880
+ $z = 3 + 4*i;
1881
+
1882
+ if you like. To create a number using the polar form, use either:
1883
+
1884
+ $z = Math::Complex->emake(5, pi/3);
1885
+ $x = cplxe(5, pi/3);
1886
+
1887
+ instead. The first argument is the modulus, the second is the angle
1888
+ (in radians, the full circle is 2*pi). (Mnemonic: C<e> is used as a
1889
+ notation for complex numbers in the polar form).
1890
+
1891
+ It is possible to write:
1892
+
1893
+ $x = cplxe(-3, pi/4);
1894
+
1895
+ but that will be silently converted into C<[3,-3pi/4]>, since the
1896
+ modulus must be non-negative (it represents the distance to the origin
1897
+ in the complex plane).
1898
+
1899
+ It is also possible to have a complex number as either argument of the
1900
+ C<make>, C<emake>, C<cplx>, and C<cplxe>: the appropriate component of
1901
+ the argument will be used.
1902
+
1903
+ $z1 = cplx(-2, 1);
1904
+ $z2 = cplx($z1, 4);
1905
+
1906
+ The C<new>, C<make>, C<emake>, C<cplx>, and C<cplxe> will also
1907
+ understand a single (string) argument of the forms
1908
+
1909
+ 2-3i
1910
+ -3i
1911
+ [2,3]
1912
+ [2,-3pi/4]
1913
+ [2]
1914
+
1915
+ in which case the appropriate cartesian and exponential components
1916
+ will be parsed from the string and used to create new complex numbers.
1917
+ The imaginary component and the theta, respectively, will default to zero.
1918
+
1919
+ The C<new>, C<make>, C<emake>, C<cplx>, and C<cplxe> will also
1920
+ understand the case of no arguments: this means plain zero or (0, 0).
1921
+
1922
+ =head1 DISPLAYING
1923
+
1924
+ When printed, a complex number is usually shown under its cartesian
1925
+ style I<a+bi>, but there are legitimate cases where the polar style
1926
+ I<[r,t]> is more appropriate. The process of converting the complex
1927
+ number into a string that can be displayed is known as I<stringification>.
1928
+
1929
+ By calling the class method C<Math::Complex::display_format> and
1930
+ supplying either C<"polar"> or C<"cartesian"> as an argument, you
1931
+ override the default display style, which is C<"cartesian">. Not
1932
+ supplying any argument returns the current settings.
1933
+
1934
+ This default can be overridden on a per-number basis by calling the
1935
+ C<display_format> method instead. As before, not supplying any argument
1936
+ returns the current display style for this number. Otherwise whatever you
1937
+ specify will be the new display style for I<this> particular number.
1938
+
1939
+ For instance:
1940
+
1941
+ use Math::Complex;
1942
+
1943
+ Math::Complex::display_format('polar');
1944
+ $j = (root(1, 3))[1];
1945
+ print "j = $j\n"; # Prints "j = [1,2pi/3]"
1946
+ $j->display_format('cartesian');
1947
+ print "j = $j\n"; # Prints "j = -0.5+0.866025403784439i"
1948
+
1949
+ The polar style attempts to emphasize arguments like I<k*pi/n>
1950
+ (where I<n> is a positive integer and I<k> an integer within [-9, +9]),
1951
+ this is called I<polar pretty-printing>.
1952
+
1953
+ For the reverse of stringifying, see the C<make> and C<emake>.
1954
+
1955
+ =head2 CHANGED IN PERL 5.6
1956
+
1957
+ The C<display_format> class method and the corresponding
1958
+ C<display_format> object method can now be called using
1959
+ a parameter hash instead of just a one parameter.
1960
+
1961
+ The old display format style, which can have values C<"cartesian"> or
1962
+ C<"polar">, can be changed using the C<"style"> parameter.
1963
+
1964
+ $j->display_format(style => "polar");
1965
+
1966
+ The one parameter calling convention also still works.
1967
+
1968
+ $j->display_format("polar");
1969
+
1970
+ There are two new display parameters.
1971
+
1972
+ The first one is C<"format">, which is a sprintf()-style format string
1973
+ to be used for both numeric parts of the complex number(s). The is
1974
+ somewhat system-dependent but most often it corresponds to C<"%.15g">.
1975
+ You can revert to the default by setting the C<format> to C<undef>.
1976
+
1977
+ # the $j from the above example
1978
+
1979
+ $j->display_format('format' => '%.5f');
1980
+ print "j = $j\n"; # Prints "j = -0.50000+0.86603i"
1981
+ $j->display_format('format' => undef);
1982
+ print "j = $j\n"; # Prints "j = -0.5+0.86603i"
1983
+
1984
+ Notice that this affects also the return values of the
1985
+ C<display_format> methods: in list context the whole parameter hash
1986
+ will be returned, as opposed to only the style parameter value.
1987
+ This is a potential incompatibility with earlier versions if you
1988
+ have been calling the C<display_format> method in list context.
1989
+
1990
+ The second new display parameter is C<"polar_pretty_print">, which can
1991
+ be set to true or false, the default being true. See the previous
1992
+ section for what this means.
1993
+
1994
+ =head1 USAGE
1995
+
1996
+ Thanks to overloading, the handling of arithmetics with complex numbers
1997
+ is simple and almost transparent.
1998
+
1999
+ Here are some examples:
2000
+
2001
+ use Math::Complex;
2002
+
2003
+ $j = cplxe(1, 2*pi/3); # $j ** 3 == 1
2004
+ print "j = $j, j**3 = ", $j ** 3, "\n";
2005
+ print "1 + j + j**2 = ", 1 + $j + $j**2, "\n";
2006
+
2007
+ $z = -16 + 0*i; # Force it to be a complex
2008
+ print "sqrt($z) = ", sqrt($z), "\n";
2009
+
2010
+ $k = exp(i * 2*pi/3);
2011
+ print "$j - $k = ", $j - $k, "\n";
2012
+
2013
+ $z->Re(3); # Re, Im, arg, abs,
2014
+ $j->arg(2); # (the last two aka rho, theta)
2015
+ # can be used also as mutators.
2016
+
2017
+ =head1 CONSTANTS
2018
+
2019
+ =head2 PI
2020
+
2021
+ The constant C<pi> and some handy multiples of it (pi2, pi4,
2022
+ and pip2 (pi/2) and pip4 (pi/4)) are also available if separately
2023
+ exported:
2024
+
2025
+ use Math::Complex ':pi';
2026
+ $third_of_circle = pi2 / 3;
2027
+
2028
+ =head2 Inf
2029
+
2030
+ The floating point infinity can be exported as a subroutine Inf():
2031
+
2032
+ use Math::Complex qw(Inf sinh);
2033
+ my $AlsoInf = Inf() + 42;
2034
+ my $AnotherInf = sinh(1e42);
2035
+ print "$AlsoInf is $AnotherInf\n" if $AlsoInf == $AnotherInf;
2036
+
2037
+ Note that the stringified form of infinity varies between platforms:
2038
+ it can be for example any of
2039
+
2040
+ inf
2041
+ infinity
2042
+ INF
2043
+ 1.#INF
2044
+
2045
+ or it can be something else.
2046
+
2047
+ Also note that in some platforms trying to use the infinity in
2048
+ arithmetic operations may result in Perl crashing because using
2049
+ an infinity causes SIGFPE or its moral equivalent to be sent.
2050
+ The way to ignore this is
2051
+
2052
+ local $SIG{FPE} = sub { };
2053
+
2054
+ =head1 ERRORS DUE TO DIVISION BY ZERO OR LOGARITHM OF ZERO
2055
+
2056
+ The division (/) and the following functions
2057
+
2058
+ log ln log10 logn
2059
+ tan sec csc cot
2060
+ atan asec acsc acot
2061
+ tanh sech csch coth
2062
+ atanh asech acsch acoth
2063
+
2064
+ cannot be computed for all arguments because that would mean dividing
2065
+ by zero or taking logarithm of zero. These situations cause fatal
2066
+ runtime errors looking like this
2067
+
2068
+ cot(0): Division by zero.
2069
+ (Because in the definition of cot(0), the divisor sin(0) is 0)
2070
+ Died at ...
2071
+
2072
+ or
2073
+
2074
+ atanh(-1): Logarithm of zero.
2075
+ Died at...
2076
+
2077
+ For the C<csc>, C<cot>, C<asec>, C<acsc>, C<acot>, C<csch>, C<coth>,
2078
+ C<asech>, C<acsch>, the argument cannot be C<0> (zero). For the
2079
+ logarithmic functions and the C<atanh>, C<acoth>, the argument cannot
2080
+ be C<1> (one). For the C<atanh>, C<acoth>, the argument cannot be
2081
+ C<-1> (minus one). For the C<atan>, C<acot>, the argument cannot be
2082
+ C<i> (the imaginary unit). For the C<atan>, C<acoth>, the argument
2083
+ cannot be C<-i> (the negative imaginary unit). For the C<tan>,
2084
+ C<sec>, C<tanh>, the argument cannot be I<pi/2 + k * pi>, where I<k>
2085
+ is any integer. atan2(0, 0) is undefined, and if the complex arguments
2086
+ are used for atan2(), a division by zero will happen if z1**2+z2**2 == 0.
2087
+
2088
+ Note that because we are operating on approximations of real numbers,
2089
+ these errors can happen when merely `too close' to the singularities
2090
+ listed above.
2091
+
2092
+ =head1 ERRORS DUE TO INDIGESTIBLE ARGUMENTS
2093
+
2094
+ The C<make> and C<emake> accept both real and complex arguments.
2095
+ When they cannot recognize the arguments they will die with error
2096
+ messages like the following
2097
+
2098
+ Math::Complex::make: Cannot take real part of ...
2099
+ Math::Complex::make: Cannot take real part of ...
2100
+ Math::Complex::emake: Cannot take rho of ...
2101
+ Math::Complex::emake: Cannot take theta of ...
2102
+
2103
+ =head1 BUGS
2104
+
2105
+ Saying C<use Math::Complex;> exports many mathematical routines in the
2106
+ caller environment and even overrides some (C<sqrt>, C<log>, C<atan2>).
2107
+ This is construed as a feature by the Authors, actually... ;-)
2108
+
2109
+ All routines expect to be given real or complex numbers. Don't attempt to
2110
+ use BigFloat, since Perl has currently no rule to disambiguate a '+'
2111
+ operation (for instance) between two overloaded entities.
2112
+
2113
+ In Cray UNICOS there is some strange numerical instability that results
2114
+ in root(), cos(), sin(), cosh(), sinh(), losing accuracy fast. Beware.
2115
+ The bug may be in UNICOS math libs, in UNICOS C compiler, in Math::Complex.
2116
+ Whatever it is, it does not manifest itself anywhere else where Perl runs.
2117
+
2118
+ =head1 SEE ALSO
2119
+
2120
+ L<Math::Trig>
2121
+
2122
+ =head1 AUTHORS
2123
+
2124
+ Daniel S. Lewart <F<lewart!at!uiuc.edu>>,
2125
+ Jarkko Hietaniemi <F<jhi!at!iki.fi>>,
2126
+ Raphael Manfredi <F<Raphael_Manfredi!at!pobox.com>>,
2127
+ Zefram <zefram@fysh.org>
2128
+
2129
+ =head1 LICENSE
2130
+
2131
+ This library is free software; you can redistribute it and/or modify
2132
+ it under the same terms as Perl itself.
2133
+
2134
+ =cut
2135
+
2136
+ 1;
2137
+
2138
+ # eof
git/usr/share/perl5/core_perl/Math/Trig.pm ADDED
@@ -0,0 +1,773 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # Trigonometric functions, mostly inherited from Math::Complex.
3
+ # -- Jarkko Hietaniemi, since April 1997
4
+ # -- Raphael Manfredi, September 1996 (indirectly: because of Math::Complex)
5
+ #
6
+
7
+ package Math::Trig;
8
+
9
+ { use 5.006; }
10
+ use strict;
11
+
12
+ use Math::Complex 1.59;
13
+ use Math::Complex qw(:trig :pi);
14
+ require Exporter;
15
+
16
+ our @ISA = qw(Exporter);
17
+
18
+ our $VERSION = 1.63;
19
+
20
+ my @angcnv = qw(rad2deg rad2grad
21
+ deg2rad deg2grad
22
+ grad2rad grad2deg);
23
+
24
+ my @areal = qw(asin_real acos_real);
25
+
26
+ our @EXPORT = (@{$Math::Complex::EXPORT_TAGS{'trig'}},
27
+ @angcnv, @areal);
28
+
29
+ my @rdlcnv = qw(cartesian_to_cylindrical
30
+ cartesian_to_spherical
31
+ cylindrical_to_cartesian
32
+ cylindrical_to_spherical
33
+ spherical_to_cartesian
34
+ spherical_to_cylindrical);
35
+
36
+ my @greatcircle = qw(
37
+ great_circle_distance
38
+ great_circle_direction
39
+ great_circle_bearing
40
+ great_circle_waypoint
41
+ great_circle_midpoint
42
+ great_circle_destination
43
+ );
44
+
45
+ my @pi = qw(pi pi2 pi4 pip2 pip4);
46
+
47
+ our @EXPORT_OK = (@rdlcnv, @greatcircle, @pi, 'Inf');
48
+
49
+ # See e.g. the following pages:
50
+ # https://www.movable-type.co.uk/scripts/latlong.html
51
+ # https://edwilliams.org/avform.htm
52
+ # https://en.wikipedia.org/wiki/Great-circle_distance
53
+
54
+ our %EXPORT_TAGS = ('radial' => [ @rdlcnv ],
55
+ 'great_circle' => [ @greatcircle ],
56
+ 'pi' => [ @pi ]);
57
+
58
+ sub _DR () { pi2/360 }
59
+ sub _RD () { 360/pi2 }
60
+ sub _DG () { 400/360 }
61
+ sub _GD () { 360/400 }
62
+ sub _RG () { 400/pi2 }
63
+ sub _GR () { pi2/400 }
64
+
65
+ #
66
+ # Truncating remainder.
67
+ #
68
+
69
+ sub _remt ($$) {
70
+ # Oh yes, POSIX::fmod() would be faster. Possibly. If it is available.
71
+ $_[0] - $_[1] * int($_[0] / $_[1]);
72
+ }
73
+
74
+ #
75
+ # Angle conversions.
76
+ #
77
+
78
+ sub rad2rad($) { _remt($_[0], pi2) }
79
+
80
+ sub deg2deg($) { _remt($_[0], 360) }
81
+
82
+ sub grad2grad($) { _remt($_[0], 400) }
83
+
84
+ sub rad2deg ($;$) { my $d = _RD * $_[0]; $_[1] ? $d : deg2deg($d) }
85
+
86
+ sub deg2rad ($;$) { my $d = _DR * $_[0]; $_[1] ? $d : rad2rad($d) }
87
+
88
+ sub grad2deg ($;$) { my $d = _GD * $_[0]; $_[1] ? $d : deg2deg($d) }
89
+
90
+ sub deg2grad ($;$) { my $d = _DG * $_[0]; $_[1] ? $d : grad2grad($d) }
91
+
92
+ sub rad2grad ($;$) { my $d = _RG * $_[0]; $_[1] ? $d : grad2grad($d) }
93
+
94
+ sub grad2rad ($;$) { my $d = _GR * $_[0]; $_[1] ? $d : rad2rad($d) }
95
+
96
+ #
97
+ # acos and asin functions which always return a real number
98
+ #
99
+
100
+ sub acos_real {
101
+ return 0 if $_[0] >= 1;
102
+ return pi if $_[0] <= -1;
103
+ return acos($_[0]);
104
+ }
105
+
106
+ sub asin_real {
107
+ return &pip2 if $_[0] >= 1;
108
+ return -&pip2 if $_[0] <= -1;
109
+ return asin($_[0]);
110
+ }
111
+
112
+ sub cartesian_to_spherical {
113
+ my ( $x, $y, $z ) = @_;
114
+
115
+ my $rho = sqrt( $x * $x + $y * $y + $z * $z );
116
+
117
+ return ( $rho,
118
+ atan2( $y, $x ),
119
+ $rho ? acos_real( $z / $rho ) : 0 );
120
+ }
121
+
122
+ sub spherical_to_cartesian {
123
+ my ( $rho, $theta, $phi ) = @_;
124
+
125
+ return ( $rho * cos( $theta ) * sin( $phi ),
126
+ $rho * sin( $theta ) * sin( $phi ),
127
+ $rho * cos( $phi ) );
128
+ }
129
+
130
+ sub spherical_to_cylindrical {
131
+ my ( $x, $y, $z ) = spherical_to_cartesian( @_ );
132
+
133
+ return ( sqrt( $x * $x + $y * $y ), $_[1], $z );
134
+ }
135
+
136
+ sub cartesian_to_cylindrical {
137
+ my ( $x, $y, $z ) = @_;
138
+
139
+ return ( sqrt( $x * $x + $y * $y ), atan2( $y, $x ), $z );
140
+ }
141
+
142
+ sub cylindrical_to_cartesian {
143
+ my ( $rho, $theta, $z ) = @_;
144
+
145
+ return ( $rho * cos( $theta ), $rho * sin( $theta ), $z );
146
+ }
147
+
148
+ sub cylindrical_to_spherical {
149
+ return ( cartesian_to_spherical( cylindrical_to_cartesian( @_ ) ) );
150
+ }
151
+
152
+ sub great_circle_distance {
153
+ my ( $theta0, $phi0, $theta1, $phi1, $rho ) = @_;
154
+
155
+ $rho = 1 unless defined $rho; # Default to the unit sphere.
156
+
157
+ my $dphi = $phi1 - $phi0;
158
+ my $dtheta = $theta1 - $theta0;
159
+
160
+ # A formula that is accurate for all distances is the following special
161
+ # case of the Vincenty formula for an ellipsoid with equal major and minor
162
+ # axes. See
163
+ # https://en.wikipedia.org/wiki/Great-circle_distance#Computational_formulas
164
+
165
+ my $c1 = sin($phi1) * sin($dtheta);
166
+ my $c2 = sin($phi1) * cos($dtheta);
167
+ my $c3 = sin($phi0) * cos($phi1) - cos($phi0) * $c2;
168
+ my $c4 = cos($phi0) * cos($phi1) + sin($phi0) * $c2;
169
+ return $rho * atan2(sqrt($c1 * $c1 + $c3 * $c3), $c4);
170
+ }
171
+
172
+ sub great_circle_direction {
173
+ my ( $theta0, $phi0, $theta1, $phi1 ) = @_;
174
+
175
+ my $lat0 = pip2 - $phi0;
176
+ my $lat1 = pip2 - $phi1;
177
+
178
+ return rad2rad(pi2 -
179
+ atan2(sin($theta0-$theta1) * cos($lat1),
180
+ cos($lat0) * sin($lat1) -
181
+ sin($lat0) * cos($lat1) * cos($theta0-$theta1)));
182
+ }
183
+
184
+ *great_circle_bearing = \&great_circle_direction;
185
+
186
+ sub great_circle_waypoint {
187
+ my ( $theta0, $phi0, $theta1, $phi1, $point ) = @_;
188
+
189
+ $point = 0.5 unless defined $point;
190
+
191
+ my $d = great_circle_distance( $theta0, $phi0, $theta1, $phi1 );
192
+
193
+ return undef if $d == pi;
194
+
195
+ my $sd = sin($d);
196
+
197
+ return ($theta0, $phi0) if $sd == 0;
198
+
199
+ my $A = sin((1 - $point) * $d) / $sd;
200
+ my $B = sin( $point * $d) / $sd;
201
+
202
+ my $lat0 = pip2 - $phi0;
203
+ my $lat1 = pip2 - $phi1;
204
+
205
+ my $x = $A * cos($lat0) * cos($theta0) + $B * cos($lat1) * cos($theta1);
206
+ my $y = $A * cos($lat0) * sin($theta0) + $B * cos($lat1) * sin($theta1);
207
+ my $z = $A * sin($lat0) + $B * sin($lat1);
208
+
209
+ my $theta = atan2($y, $x);
210
+ my $phi = acos_real($z);
211
+
212
+ return ($theta, $phi);
213
+ }
214
+
215
+ sub great_circle_midpoint {
216
+ great_circle_waypoint(@_[0..3], 0.5);
217
+ }
218
+
219
+ sub great_circle_destination {
220
+ my ( $theta0, $phi0, $dir0, $dst ) = @_;
221
+
222
+ my $lat0 = pip2 - $phi0;
223
+
224
+ my $phi1 = asin_real(sin($lat0)*cos($dst) +
225
+ cos($lat0)*sin($dst)*cos($dir0));
226
+
227
+ my $theta1 = $theta0 + atan2(sin($dir0)*sin($dst)*cos($lat0),
228
+ cos($dst)-sin($lat0)*sin($phi1));
229
+
230
+ my $dir1 = great_circle_bearing($theta1, $phi1, $theta0, $phi0) + pi;
231
+
232
+ $dir1 -= pi2 if $dir1 > pi2;
233
+
234
+ return ($theta1, $phi1, $dir1);
235
+ }
236
+
237
+ 1;
238
+
239
+ __END__
240
+ =pod
241
+
242
+ =head1 NAME
243
+
244
+ Math::Trig - trigonometric functions
245
+
246
+ =head1 SYNOPSIS
247
+
248
+ use Math::Trig;
249
+
250
+ $x = tan(0.9);
251
+ $y = acos(3.7);
252
+ $z = asin(2.4);
253
+
254
+ $halfpi = pi/2;
255
+
256
+ $rad = deg2rad(120);
257
+
258
+ # Import constants pi2, pi4, pip2, pip4 (2*pi, 4*pi, pi/2, pi/4).
259
+ use Math::Trig ':pi';
260
+
261
+ # Import the conversions between cartesian/spherical/cylindrical.
262
+ use Math::Trig ':radial';
263
+
264
+ # Import the great circle formulas.
265
+ use Math::Trig ':great_circle';
266
+
267
+ =head1 DESCRIPTION
268
+
269
+ C<Math::Trig> defines many trigonometric functions not defined by the
270
+ core Perl which defines only the C<sin()> and C<cos()>. The constant
271
+ B<pi> is also defined as are a few convenience functions for angle
272
+ conversions, and I<great circle formulas> for spherical movement.
273
+
274
+ =head1 TRIGONOMETRIC FUNCTIONS
275
+
276
+ The tangent
277
+
278
+ =over 4
279
+
280
+ =item B<tan>
281
+
282
+ =back
283
+
284
+ The cofunctions of the sine, cosine, and tangent (cosec/csc and cotan/cot
285
+ are aliases)
286
+
287
+ B<csc>, B<cosec>, B<sec>, B<sec>, B<cot>, B<cotan>
288
+
289
+ The arcus (also known as the inverse) functions of the sine, cosine,
290
+ and tangent
291
+
292
+ B<asin>, B<acos>, B<atan>
293
+
294
+ The principal value of the arc tangent of y/x
295
+
296
+ B<atan2>(y, x)
297
+
298
+ The arcus cofunctions of the sine, cosine, and tangent (acosec/acsc
299
+ and acotan/acot are aliases). Note that atan2(0, 0) is not well-defined.
300
+
301
+ B<acsc>, B<acosec>, B<asec>, B<acot>, B<acotan>
302
+
303
+ The hyperbolic sine, cosine, and tangent
304
+
305
+ B<sinh>, B<cosh>, B<tanh>
306
+
307
+ The cofunctions of the hyperbolic sine, cosine, and tangent (cosech/csch
308
+ and cotanh/coth are aliases)
309
+
310
+ B<csch>, B<cosech>, B<sech>, B<coth>, B<cotanh>
311
+
312
+ The area (also known as the inverse) functions of the hyperbolic
313
+ sine, cosine, and tangent
314
+
315
+ B<asinh>, B<acosh>, B<atanh>
316
+
317
+ The area cofunctions of the hyperbolic sine, cosine, and tangent
318
+ (acsch/acosech and acoth/acotanh are aliases)
319
+
320
+ B<acsch>, B<acosech>, B<asech>, B<acoth>, B<acotanh>
321
+
322
+ The trigonometric constant B<pi> and some of handy multiples
323
+ of it are also defined.
324
+
325
+ B<pi, pi2, pi4, pip2, pip4>
326
+
327
+ =head2 ERRORS DUE TO DIVISION BY ZERO
328
+
329
+ The following functions
330
+
331
+ acoth
332
+ acsc
333
+ acsch
334
+ asec
335
+ asech
336
+ atanh
337
+ cot
338
+ coth
339
+ csc
340
+ csch
341
+ sec
342
+ sech
343
+ tan
344
+ tanh
345
+
346
+ cannot be computed for all arguments because that would mean dividing
347
+ by zero or taking logarithm of zero. These situations cause fatal
348
+ runtime errors looking like this
349
+
350
+ cot(0): Division by zero.
351
+ (Because in the definition of cot(0), the divisor sin(0) is 0)
352
+ Died at ...
353
+
354
+ or
355
+
356
+ atanh(-1): Logarithm of zero.
357
+ Died at...
358
+
359
+ For the C<csc>, C<cot>, C<asec>, C<acsc>, C<acot>, C<csch>, C<coth>,
360
+ C<asech>, C<acsch>, the argument cannot be C<0> (zero). For the
361
+ C<atanh>, C<acoth>, the argument cannot be C<1> (one). For the
362
+ C<atanh>, C<acoth>, the argument cannot be C<-1> (minus one). For the
363
+ C<tan>, C<sec>, C<tanh>, C<sech>, the argument cannot be I<pi/2 + k *
364
+ pi>, where I<k> is any integer.
365
+
366
+ Note that atan2(0, 0) is not well-defined.
367
+
368
+ =head2 SIMPLE (REAL) ARGUMENTS, COMPLEX RESULTS
369
+
370
+ Please note that some of the trigonometric functions can break out
371
+ from the B<real axis> into the B<complex plane>. For example
372
+ C<asin(2)> has no definition for plain real numbers but it has
373
+ definition for complex numbers.
374
+
375
+ In Perl terms this means that supplying the usual Perl numbers (also
376
+ known as scalars, please see L<perldata>) as input for the
377
+ trigonometric functions might produce as output results that no more
378
+ are simple real numbers: instead they are complex numbers.
379
+
380
+ The C<Math::Trig> handles this by using the C<Math::Complex> package
381
+ which knows how to handle complex numbers, please see L<Math::Complex>
382
+ for more information. In practice you need not to worry about getting
383
+ complex numbers as results because the C<Math::Complex> takes care of
384
+ details like for example how to display complex numbers. For example:
385
+
386
+ print asin(2), "\n";
387
+
388
+ should produce something like this (take or leave few last decimals):
389
+
390
+ 1.5707963267949-1.31695789692482i
391
+
392
+ That is, a complex number with the real part of approximately C<1.571>
393
+ and the imaginary part of approximately C<-1.317>.
394
+
395
+ =head1 PLANE ANGLE CONVERSIONS
396
+
397
+ (Plane, 2-dimensional) angles may be converted with the following functions.
398
+
399
+ =over
400
+
401
+ =item deg2rad
402
+
403
+ $radians = deg2rad($degrees);
404
+
405
+ =item grad2rad
406
+
407
+ $radians = grad2rad($gradians);
408
+
409
+ =item rad2deg
410
+
411
+ $degrees = rad2deg($radians);
412
+
413
+ =item grad2deg
414
+
415
+ $degrees = grad2deg($gradians);
416
+
417
+ =item deg2grad
418
+
419
+ $gradians = deg2grad($degrees);
420
+
421
+ =item rad2grad
422
+
423
+ $gradians = rad2grad($radians);
424
+
425
+ =back
426
+
427
+ The full circle is 2 I<pi> radians or I<360> degrees or I<400> gradians.
428
+ The result is by default wrapped to be inside the [0, {2pi,360,400}) circle.
429
+ If you don't want this, supply a true second argument:
430
+
431
+ $zillions_of_radians = deg2rad($zillions_of_degrees, 1);
432
+ $negative_degrees = rad2deg($negative_radians, 1);
433
+
434
+ You can also do the wrapping explicitly by rad2rad(), deg2deg(), and
435
+ grad2grad().
436
+
437
+ =over 4
438
+
439
+ =item rad2rad
440
+
441
+ $radians_wrapped_by_2pi = rad2rad($radians);
442
+
443
+ =item deg2deg
444
+
445
+ $degrees_wrapped_by_360 = deg2deg($degrees);
446
+
447
+ =item grad2grad
448
+
449
+ $gradians_wrapped_by_400 = grad2grad($gradians);
450
+
451
+ =back
452
+
453
+ =head1 RADIAL COORDINATE CONVERSIONS
454
+
455
+ B<Radial coordinate systems> are the B<spherical> and the B<cylindrical>
456
+ systems, explained shortly in more detail.
457
+
458
+ You can import radial coordinate conversion functions by using the
459
+ C<:radial> tag:
460
+
461
+ use Math::Trig ':radial';
462
+
463
+ ($rho, $theta, $z) = cartesian_to_cylindrical($x, $y, $z);
464
+ ($rho, $theta, $phi) = cartesian_to_spherical($x, $y, $z);
465
+ ($x, $y, $z) = cylindrical_to_cartesian($rho, $theta, $z);
466
+ ($rho_s, $theta, $phi) = cylindrical_to_spherical($rho_c, $theta, $z);
467
+ ($x, $y, $z) = spherical_to_cartesian($rho, $theta, $phi);
468
+ ($rho_c, $theta, $z) = spherical_to_cylindrical($rho_s, $theta, $phi);
469
+
470
+ B<All angles are in radians>.
471
+
472
+ =head2 COORDINATE SYSTEMS
473
+
474
+ B<Cartesian> coordinates are the usual rectangular I<(x, y, z)>-coordinates.
475
+
476
+ Spherical coordinates, I<(rho, theta, phi)>, are three-dimensional
477
+ coordinates which define a point in three-dimensional space. They are
478
+ based on a sphere surface. The radius of the sphere is B<rho>, also
479
+ known as the I<radial> coordinate. The angle in the I<xy>-plane
480
+ (around the I<z>-axis) is B<theta>, also known as the I<azimuthal>
481
+ coordinate. The angle from the I<z>-axis is B<phi>, also known as the
482
+ I<polar> coordinate. The North Pole is therefore I<rho, 0, 0>, and
483
+ the Gulf of Guinea (think of the missing big chunk of Africa) I<rho,
484
+ 0, pi/2>. In geographical terms I<phi> is latitude (northward
485
+ positive, southward negative) and I<theta> is longitude (eastward
486
+ positive, westward negative).
487
+
488
+ B<BEWARE>: some texts define I<theta> and I<phi> the other way round,
489
+ some texts define the I<phi> to start from the horizontal plane, some
490
+ texts use I<r> in place of I<rho>.
491
+
492
+ Cylindrical coordinates, I<(rho, theta, z)>, are three-dimensional
493
+ coordinates which define a point in three-dimensional space. They are
494
+ based on a cylinder surface. The radius of the cylinder is B<rho>,
495
+ also known as the I<radial> coordinate. The angle in the I<xy>-plane
496
+ (around the I<z>-axis) is B<theta>, also known as the I<azimuthal>
497
+ coordinate. The third coordinate is the I<z>, pointing up from the
498
+ B<theta>-plane.
499
+
500
+ =head2 3-D ANGLE CONVERSIONS
501
+
502
+ Conversions to and from spherical and cylindrical coordinates are
503
+ available. Please notice that the conversions are not necessarily
504
+ reversible because of the equalities like I<pi> angles being equal to
505
+ I<-pi> angles.
506
+
507
+ =over 4
508
+
509
+ =item cartesian_to_cylindrical
510
+
511
+ ($rho, $theta, $z) = cartesian_to_cylindrical($x, $y, $z);
512
+
513
+ =item cartesian_to_spherical
514
+
515
+ ($rho, $theta, $phi) = cartesian_to_spherical($x, $y, $z);
516
+
517
+ =item cylindrical_to_cartesian
518
+
519
+ ($x, $y, $z) = cylindrical_to_cartesian($rho, $theta, $z);
520
+
521
+ =item cylindrical_to_spherical
522
+
523
+ ($rho_s, $theta, $phi) = cylindrical_to_spherical($rho_c, $theta, $z);
524
+
525
+ Notice that when C<$z> is not 0 C<$rho_s> is not equal to C<$rho_c>.
526
+
527
+ =item spherical_to_cartesian
528
+
529
+ ($x, $y, $z) = spherical_to_cartesian($rho, $theta, $phi);
530
+
531
+ =item spherical_to_cylindrical
532
+
533
+ ($rho_c, $theta, $z) = spherical_to_cylindrical($rho_s, $theta, $phi);
534
+
535
+ Notice that when C<$z> is not 0 C<$rho_c> is not equal to C<$rho_s>.
536
+
537
+ =back
538
+
539
+ =head1 GREAT CIRCLE DISTANCES AND DIRECTIONS
540
+
541
+ A great circle is section of a circle that contains the circle
542
+ diameter: the shortest distance between two (non-antipodal) points on
543
+ the spherical surface goes along the great circle connecting those two
544
+ points.
545
+
546
+ =head2 great_circle_distance
547
+
548
+ Returns the great circle distance between two points on a sphere.
549
+
550
+ $distance = great_circle_distance($theta0, $phi0, $theta1, $phi1, [, $rho]);
551
+
552
+ Where ($theta0, $phi0) and ($theta1, $phi1) are the spherical coordinates of
553
+ the two points, respectively. The distance is in C<$rho> units. The C<$rho>
554
+ is optional. It defaults to 1 (the unit sphere).
555
+
556
+ If you are using geographic coordinates, latitude and longitude, you need to
557
+ adjust for the fact that latitude is zero at the equator increasing towards
558
+ the north and decreasing towards the south. Assuming ($lat0, $lon0) and
559
+ ($lat1, $lon1) are the geographic coordinates in radians of the two points,
560
+ the distance can be computed with
561
+
562
+ $distance = great_circle_distance($lon0, pi/2 - $lat0,
563
+ $lon1, pi/2 - $lat1, $rho);
564
+
565
+ =head2 great_circle_direction
566
+
567
+ The direction you must follow the great circle (also known as I<bearing>)
568
+ can be computed by the great_circle_direction() function:
569
+
570
+ use Math::Trig 'great_circle_direction';
571
+
572
+ $direction = great_circle_direction($theta0, $phi0, $theta1, $phi1);
573
+
574
+ =head2 great_circle_bearing
575
+
576
+ Alias 'great_circle_bearing' for 'great_circle_direction' is also available.
577
+
578
+ use Math::Trig 'great_circle_bearing';
579
+
580
+ $direction = great_circle_bearing($theta0, $phi0, $theta1, $phi1);
581
+
582
+ The result of great_circle_direction is in radians, zero indicating
583
+ straight north, pi or -pi straight south, pi/2 straight west, and
584
+ -pi/2 straight east.
585
+
586
+ =head2 great_circle_destination
587
+
588
+ You can inversely compute the destination if you know the
589
+ starting point, direction, and distance:
590
+
591
+ use Math::Trig 'great_circle_destination';
592
+
593
+ # $diro is the original direction,
594
+ # for example from great_circle_bearing().
595
+ # $distance is the angular distance in radians,
596
+ # for example from great_circle_distance().
597
+ # $thetad and $phid are the destination coordinates,
598
+ # $dird is the final direction at the destination.
599
+
600
+ ($thetad, $phid, $dird) =
601
+ great_circle_destination($theta, $phi, $diro, $distance);
602
+
603
+ or the midpoint if you know the end points:
604
+
605
+ =head2 great_circle_midpoint
606
+
607
+ use Math::Trig 'great_circle_midpoint';
608
+
609
+ ($thetam, $phim) =
610
+ great_circle_midpoint($theta0, $phi0, $theta1, $phi1);
611
+
612
+ The great_circle_midpoint() is just a special case of
613
+
614
+ =head2 great_circle_waypoint
615
+
616
+ use Math::Trig 'great_circle_waypoint';
617
+
618
+ ($thetai, $phii) =
619
+ great_circle_waypoint($theta0, $phi0, $theta1, $phi1, $way);
620
+
621
+ Where $way indicates the position of the waypoint along the great
622
+ circle arc through the starting point ($theta0, $phi0) and the end
623
+ point ($theta1, $phi1) relative to the distance from the starting
624
+ point to the end point. So $way = 0 gives the starting point, $way = 1
625
+ gives the end point, $way < 0 gives a point "behind" the starting
626
+ point, and $way > 1 gives a point beyond the end point. $way defaults
627
+ to 0.5 if not given.
628
+
629
+ Note that antipodal points (where their distance is I<pi> radians) do
630
+ not have unique waypoints between them, and therefore C<undef> is
631
+ returned in such cases. If the points are the same, so the distance
632
+ between them is zero, all waypoints are identical to the starting/end
633
+ point.
634
+
635
+ The thetas, phis, direction, and distance in the above are all in
636
+ radians.
637
+
638
+ You can import all the great circle formulas by
639
+
640
+ use Math::Trig ':great_circle';
641
+
642
+ Notice that the resulting directions might be somewhat surprising if
643
+ you are looking at a flat worldmap: in such map projections the great
644
+ circles quite often do not look like the shortest routes -- but for
645
+ example the shortest possible routes from Europe or North America to
646
+ Asia do often cross the polar regions. (The common Mercator projection
647
+ does B<not> show great circles as straight lines: straight lines in the
648
+ Mercator projection are lines of constant bearing.)
649
+
650
+ =head1 EXAMPLES
651
+
652
+ To calculate the distance between London (51.3N 0.5W) and Tokyo
653
+ (35.7N 139.8E) in kilometers:
654
+
655
+ use Math::Trig qw(great_circle_distance deg2rad);
656
+
657
+ # Notice the 90 - latitude: phi zero is at the North Pole.
658
+ sub NESW { deg2rad($_[0]), deg2rad(90 - $_[1]) }
659
+ my @L = NESW( -0.5, 51.3);
660
+ my @T = NESW(139.8, 35.7);
661
+ my $km = great_circle_distance(@L, @T, 6378); # About 9600 km.
662
+
663
+ The direction you would have to go from London to Tokyo (in radians,
664
+ straight north being zero, straight east being pi/2).
665
+
666
+ use Math::Trig qw(great_circle_direction);
667
+
668
+ my $rad = great_circle_direction(@L, @T); # About 0.547 or 0.174 pi.
669
+
670
+ The midpoint between London and Tokyo being
671
+
672
+ use Math::Trig qw(great_circle_midpoint rad2deg);
673
+
674
+ my @M = great_circle_midpoint(@L, @T);
675
+ sub SWNE { rad2deg( $_[0] ), 90 - rad2deg( $_[1] ) }
676
+ my @lonlat = SWNE(@M);
677
+
678
+ or about 69 N 89 E, on the Putorana Plateau of Siberia.
679
+
680
+ B<NOTE>: you B<cannot> get from A to B like this:
681
+
682
+ Dist = great_circle_distance(A, B)
683
+ Dir = great_circle_direction(A, B)
684
+ C = great_circle_destination(A, Dist, Dir)
685
+
686
+ and expect C to be B, because the bearing constantly changes when
687
+ going from A to B (except in some special case like the meridians or
688
+ the circles of latitudes) and in great_circle_destination() one gives
689
+ a B<constant> bearing to follow.
690
+
691
+ =head2 CAVEAT FOR GREAT CIRCLE FORMULAS
692
+
693
+ The answers may be off by few percentages because of the irregular
694
+ (slightly aspherical) form of the Earth. The errors are at worst
695
+ about 0.55%, but generally below 0.3%.
696
+
697
+ =head2 Real-valued asin and acos
698
+
699
+ For small inputs asin() and acos() may return complex numbers even
700
+ when real numbers would be enough and correct, this happens because of
701
+ floating-point inaccuracies. You can see these inaccuracies for
702
+ example by trying theses:
703
+
704
+ print cos(1e-6)**2+sin(1e-6)**2 - 1,"\n";
705
+ printf "%.20f", cos(1e-6)**2+sin(1e-6)**2,"\n";
706
+
707
+ which will print something like this
708
+
709
+ -1.11022302462516e-16
710
+ 0.99999999999999988898
711
+
712
+ even though the expected results are of course exactly zero and one.
713
+ The formulas used to compute asin() and acos() are quite sensitive to
714
+ this, and therefore they might accidentally slip into the complex
715
+ plane even when they should not. To counter this there are two
716
+ interfaces that are guaranteed to return a real-valued output.
717
+
718
+ =over 4
719
+
720
+ =item asin_real
721
+
722
+ use Math::Trig qw(asin_real);
723
+
724
+ $real_angle = asin_real($input_sin);
725
+
726
+ Return a real-valued arcus sine if the input is between [-1, 1],
727
+ B<inclusive> the endpoints. For inputs greater than one, pi/2
728
+ is returned. For inputs less than minus one, -pi/2 is returned.
729
+
730
+ =item acos_real
731
+
732
+ use Math::Trig qw(acos_real);
733
+
734
+ $real_angle = acos_real($input_cos);
735
+
736
+ Return a real-valued arcus cosine if the input is between [-1, 1],
737
+ B<inclusive> the endpoints. For inputs greater than one, zero
738
+ is returned. For inputs less than minus one, pi is returned.
739
+
740
+ =back
741
+
742
+ =head1 BUGS
743
+
744
+ Saying C<use Math::Trig;> exports many mathematical routines in the
745
+ caller environment and even overrides some (C<sin>, C<cos>). This is
746
+ construed as a feature by the Authors, actually... ;-)
747
+
748
+ The code is not optimized for speed, especially because we use
749
+ C<Math::Complex> and thus go quite near complex numbers while doing
750
+ the computations even when the arguments are not. This, however,
751
+ cannot be completely avoided if we want things like C<asin(2)> to give
752
+ an answer instead of giving a fatal runtime error.
753
+
754
+ Do not attempt navigation using these formulas.
755
+
756
+ =head1 SEE ALSO
757
+
758
+ L<Math::Complex>
759
+
760
+ =head1 AUTHORS
761
+
762
+ Jarkko Hietaniemi <F<jhi!at!iki.fi>>,
763
+ Raphael Manfredi <F<Raphael_Manfredi!at!pobox.com>>,
764
+ Zefram <zefram@fysh.org>
765
+
766
+ =head1 LICENSE
767
+
768
+ This library is free software; you can redistribute it and/or modify
769
+ it under the same terms as Perl itself.
770
+
771
+ =cut
772
+
773
+ # eof
git/usr/share/perl5/core_perl/Memoize/AnyDBM_File.pm ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ use strict; use warnings;
2
+
3
+ package Memoize::AnyDBM_File;
4
+ our $VERSION = '1.17';
5
+
6
+ our @ISA = qw(DB_File GDBM_File Memoize::NDBM_File SDBM_File ODBM_File) unless @ISA;
7
+
8
+ for my $mod (@ISA) {
9
+ if (eval "require $mod") {
10
+ $mod = 'NDBM_File'
11
+ if $mod eq 'Memoize::NDBM_File'
12
+ and eval { NDBM_File->VERSION( '1.16' ) };
13
+ print STDERR "AnyDBM_File => Selected $mod.\n" if our $Verbose;
14
+ @ISA = $mod;
15
+ return 1;
16
+ }
17
+ }
18
+
19
+ die "No DBM package was successfully found or installed";
20
+
21
+ __END__
22
+
23
+ =pod
24
+
25
+ =head1 NAME
26
+
27
+ Memoize::AnyDBM_File - glue to provide EXISTS for AnyDBM_File for Storable use
28
+
29
+ =head1 DESCRIPTION
30
+
31
+ This class does the same thing as L<AnyDBM_File>, except that instead of
32
+ L<NDBM_File> itself it loads L<Memoize::NDBM_File> if L<NDBM_File> lacks
33
+ L<EXISTS|perltie/C<EXISTS>> support.
34
+
35
+ Code which requires perl 5.37.3 or newer should simply use L<AnyBDM_File> directly.
36
+
37
+ =cut
git/usr/share/perl5/core_perl/Memoize/Expire.pm ADDED
@@ -0,0 +1,352 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ use strict; use warnings;
2
+
3
+ package Memoize::Expire;
4
+ our $VERSION = '1.17';
5
+
6
+ use Carp;
7
+ our $DEBUG;
8
+
9
+ # The format of the metadata is:
10
+ # (4-byte number of last-access-time) (For LRU when I implement it)
11
+ # (4-byte expiration time: unsigned seconds-since-unix-epoch)
12
+ # (2-byte number-of-uses-before-expire)
13
+
14
+ BEGIN {
15
+ eval {require Time::HiRes};
16
+ unless ($@) {
17
+ Time::HiRes->import('time');
18
+ }
19
+ }
20
+
21
+ sub TIEHASH {
22
+ my ($package, %args) = @_;
23
+ my %cache;
24
+ if ($args{TIE}) {
25
+ my ($module, @opts) = @{$args{TIE}};
26
+ my $modulefile = $module . '.pm';
27
+ $modulefile =~ s{::}{/}g;
28
+ eval { require $modulefile };
29
+ if ($@) {
30
+ croak "Memoize::Expire: Couldn't load hash tie module `$module': $@; aborting";
31
+ }
32
+ my $rc = (tie %cache => $module, @opts);
33
+ unless ($rc) {
34
+ croak "Memoize::Expire: Couldn't tie hash to `$module': $@; aborting";
35
+ }
36
+ }
37
+ $args{LIFETIME} ||= 0;
38
+ $args{NUM_USES} ||= 0;
39
+ $args{C} = delete $args{HASH} || \%cache;
40
+ bless \%args => $package;
41
+ }
42
+
43
+ sub STORE {
44
+ $DEBUG and print STDERR " >> Store $_[1] $_[2]\n";
45
+ my ($self, $key, $value) = @_;
46
+ my $expire_time = $self->{LIFETIME} > 0 ? $self->{LIFETIME} + time : 0;
47
+ # The call that results in a value to store into the cache is the
48
+ # first of the NUM_USES allowed calls.
49
+ my $header = _make_header(time, $expire_time, $self->{NUM_USES}-1);
50
+ @{$self->{C}}{"H$key", "V$key"} = ($header, $value);
51
+ $value;
52
+ }
53
+
54
+ sub FETCH {
55
+ $DEBUG and print STDERR " >> Fetch cached value for $_[1]\n";
56
+ my ($last_access, $expire_time, $num_uses_left) = _get_header($_[0]{C}{"H$_[1]"});
57
+ $DEBUG and print STDERR " >> (ttl: ", ($expire_time-time()), ", nuses: $num_uses_left)\n";
58
+ $_[0]{C}{"H$_[1]"} = _make_header(time, $expire_time, --$num_uses_left);
59
+ $_[0]{C}{"V$_[1]"};
60
+ }
61
+
62
+ sub EXISTS {
63
+ $DEBUG and print STDERR " >> Exists $_[1]\n";
64
+ unless (exists $_[0]{C}{"V$_[1]"}) {
65
+ $DEBUG and print STDERR " Not in underlying hash at all.\n";
66
+ return 0;
67
+ }
68
+ my $item = $_[0]{C}{"H$_[1]"};
69
+ my ($last_access, $expire_time, $num_uses_left) = _get_header($item);
70
+ my $ttl = $expire_time - time;
71
+ if ($DEBUG) {
72
+ $_[0]{LIFETIME} and print STDERR " Time to live for this item: $ttl\n";
73
+ $_[0]{NUM_USES} and print STDERR " Uses remaining: $num_uses_left\n";
74
+ }
75
+ if ( (! $_[0]{LIFETIME} || $expire_time > time)
76
+ && (! $_[0]{NUM_USES} || $num_uses_left > 0 )) {
77
+ $DEBUG and print STDERR " (Still good)\n";
78
+ return 1;
79
+ } else {
80
+ $DEBUG and print STDERR " (Expired)\n";
81
+ return 0;
82
+ }
83
+ }
84
+
85
+ sub FIRSTKEY {
86
+ scalar keys %{$_[0]{C}};
87
+ &NEXTKEY;
88
+ }
89
+
90
+ sub NEXTKEY {
91
+ while (defined(my $key = each %{$_[0]{C}})) {
92
+ return substr $key, 1 if 'V' eq substr $key, 0, 1;
93
+ }
94
+ undef;
95
+ }
96
+
97
+ # Arguments: last access time, expire time, number of uses remaining
98
+ sub _make_header {
99
+ pack "N N n", @_;
100
+ }
101
+
102
+ # Return last access time, expire time, number of uses remaining
103
+ sub _get_header {
104
+ unpack "N N n", substr($_[0], 0, 10);
105
+ }
106
+
107
+ 1;
108
+
109
+ __END__
110
+
111
+ =pod
112
+
113
+ =head1 NAME
114
+
115
+ Memoize::Expire - Plug-in module for automatic expiration of memoized values
116
+
117
+ =head1 SYNOPSIS
118
+
119
+ use Memoize;
120
+ use Memoize::Expire;
121
+ tie my %cache => 'Memoize::Expire',
122
+ LIFETIME => $lifetime, # In seconds
123
+ NUM_USES => $n_uses;
124
+
125
+ memoize 'function', SCALAR_CACHE => [HASH => \%cache ];
126
+
127
+ =head1 DESCRIPTION
128
+
129
+ Memoize::Expire is a plug-in module for Memoize. It allows the cached
130
+ values for memoized functions to expire automatically. This manual
131
+ assumes you are already familiar with the Memoize module. If not, you
132
+ should study that manual carefully first, paying particular attention
133
+ to the HASH feature.
134
+
135
+ Memoize::Expire is a layer of software that you can insert in between
136
+ Memoize itself and whatever underlying package implements the cache.
137
+ The layer presents a hash variable whose values expire whenever they
138
+ get too old, have been used too often, or both. You tell C<Memoize> to
139
+ use this forgetful hash as its cache instead of the default, which is
140
+ an ordinary hash.
141
+
142
+ To specify a real-time timeout, supply the C<LIFETIME> option with a
143
+ numeric value. Cached data will expire after this many seconds, and
144
+ will be looked up afresh when it expires. When a data item is looked
145
+ up afresh, its lifetime is reset.
146
+
147
+ If you specify C<NUM_USES> with an argument of I<n>, then each cached
148
+ data item will be discarded and looked up afresh after the I<n>th time
149
+ you access it. When a data item is looked up afresh, its number of
150
+ uses is reset.
151
+
152
+ If you specify both arguments, data will be discarded from the cache
153
+ when either expiration condition holds.
154
+
155
+ Memoize::Expire uses a real hash internally to store the cached data.
156
+ You can use the C<HASH> option to Memoize::Expire to supply a tied
157
+ hash in place of the ordinary hash that Memoize::Expire will normally
158
+ use. You can use this feature to add Memoize::Expire as a layer in
159
+ between a persistent disk hash and Memoize. If you do this, you get a
160
+ persistent disk cache whose entries expire automatically. For
161
+ example:
162
+
163
+ # Memoize
164
+ # |
165
+ # Memoize::Expire enforces data expiration policy
166
+ # |
167
+ # DB_File implements persistence of data in a disk file
168
+ # |
169
+ # Disk file
170
+
171
+ use Memoize;
172
+ use Memoize::Expire;
173
+ use DB_File;
174
+
175
+ # Set up persistence
176
+ tie my %disk_cache => 'DB_File', $filename, O_CREAT|O_RDWR, 0666];
177
+
178
+ # Set up expiration policy, supplying persistent hash as a target
179
+ tie my %cache => 'Memoize::Expire',
180
+ LIFETIME => $lifetime, # In seconds
181
+ NUM_USES => $n_uses,
182
+ HASH => \%disk_cache;
183
+
184
+ # Set up memoization, supplying expiring persistent hash for cache
185
+ memoize 'function', SCALAR_CACHE => [ HASH => \%cache ];
186
+
187
+ =head1 INTERFACE
188
+
189
+ There is nothing special about Memoize::Expire. It is just an
190
+ example. If you don't like the policy that it implements, you are
191
+ free to write your own expiration policy module that implements
192
+ whatever policy you desire. Here is how to do that. Let us suppose
193
+ that your module will be named MyExpirePolicy.
194
+
195
+ Short summary: You need to create a package that defines four methods:
196
+
197
+ =over 4
198
+
199
+ =item
200
+ TIEHASH
201
+
202
+ Construct and return cache object.
203
+
204
+ =item
205
+ EXISTS
206
+
207
+ Given a function argument, is the corresponding function value in the
208
+ cache, and if so, is it fresh enough to use?
209
+
210
+ =item
211
+ FETCH
212
+
213
+ Given a function argument, look up the corresponding function value in
214
+ the cache and return it.
215
+
216
+ =item
217
+ STORE
218
+
219
+ Given a function argument and the corresponding function value, store
220
+ them into the cache.
221
+
222
+ =item
223
+ CLEAR
224
+
225
+ (Optional.) Flush the cache completely.
226
+
227
+ =back
228
+
229
+ The user who wants the memoization cache to be expired according to
230
+ your policy will say so by writing
231
+
232
+ tie my %cache => 'MyExpirePolicy', args...;
233
+ memoize 'function', SCALAR_CACHE => [HASH => \%cache];
234
+
235
+ This will invoke C<< MyExpirePolicy->TIEHASH(args) >>.
236
+ MyExpirePolicy::TIEHASH should do whatever is appropriate to set up
237
+ the cache, and it should return the cache object to the caller.
238
+
239
+ For example, MyExpirePolicy::TIEHASH might create an object that
240
+ contains a regular Perl hash (which it will to store the cached
241
+ values) and some extra information about the arguments and how old the
242
+ data is and things like that. Let us call this object I<C<C>>.
243
+
244
+ When Memoize needs to check to see if an entry is in the cache
245
+ already, it will invoke C<< C->EXISTS(key) >>. C<key> is the normalized
246
+ function argument. MyExpirePolicy::EXISTS should return 0 if the key
247
+ is not in the cache, or if it has expired, and 1 if an unexpired value
248
+ is in the cache. It should I<not> return C<undef>, because there is a
249
+ bug in some versions of Perl that will cause a spurious FETCH if the
250
+ EXISTS method returns C<undef>.
251
+
252
+ If your EXISTS function returns true, Memoize will try to fetch the
253
+ cached value by invoking C<< C->FETCH(key) >>. MyExpirePolicy::FETCH should
254
+ return the cached value. Otherwise, Memoize will call the memoized
255
+ function to compute the appropriate value, and will store it into the
256
+ cache by calling C<< C->STORE(key, value) >>.
257
+
258
+ Here is a very brief example of a policy module that expires each
259
+ cache item after ten seconds.
260
+
261
+ package Memoize::TenSecondExpire;
262
+
263
+ sub TIEHASH {
264
+ my ($package, %args) = @_;
265
+ my $cache = $args{HASH} || {};
266
+ bless $cache => $package;
267
+ }
268
+
269
+ sub EXISTS {
270
+ my ($cache, $key) = @_;
271
+ if (exists $cache->{$key} &&
272
+ $cache->{$key}{EXPIRE_TIME} > time) {
273
+ return 1
274
+ } else {
275
+ return 0; # Do NOT return undef here
276
+ }
277
+ }
278
+
279
+ sub FETCH {
280
+ my ($cache, $key) = @_;
281
+ return $cache->{$key}{VALUE};
282
+ }
283
+
284
+ sub STORE {
285
+ my ($cache, $key, $newvalue) = @_;
286
+ $cache->{$key}{VALUE} = $newvalue;
287
+ $cache->{$key}{EXPIRE_TIME} = time + 10;
288
+ }
289
+
290
+ To use this expiration policy, the user would say
291
+
292
+ use Memoize;
293
+ tie my %cache10sec => 'Memoize::TenSecondExpire';
294
+ memoize 'function', SCALAR_CACHE => [HASH => \%cache10sec];
295
+
296
+ Memoize would then call C<function> whenever a cached value was
297
+ entirely absent or was older than ten seconds.
298
+
299
+ You should always support a C<HASH> argument to C<TIEHASH> that ties
300
+ the underlying cache so that the user can specify that the cache is
301
+ also persistent or that it has some other interesting semantics. The
302
+ example above demonstrates how to do this, as does C<Memoize::Expire>.
303
+
304
+ Another sample module, L<Memoize::Saves>, is available in a separate
305
+ distribution on CPAN. It implements a policy that allows you to
306
+ specify that certain function values would always be looked up afresh.
307
+ See the documentation for details.
308
+
309
+ =head1 ALTERNATIVES
310
+
311
+ Brent Powers has a L<Memoize::ExpireLRU> module that was designed to
312
+ work with Memoize and provides expiration of least-recently-used data.
313
+ The cache is held at a fixed number of entries, and when new data
314
+ comes in, the least-recently used data is expired.
315
+
316
+ Joshua Chamas's Tie::Cache module may be useful as an expiration
317
+ manager. (If you try this, let me know how it works out.)
318
+
319
+ If you develop any useful expiration managers that you think should be
320
+ distributed with Memoize, please let me know.
321
+
322
+ =head1 CAVEATS
323
+
324
+ This module is experimental, and may contain bugs. Please report bugs
325
+ to the address below.
326
+
327
+ Number-of-uses is stored as a 16-bit unsigned integer, so can't exceed
328
+ 65535.
329
+
330
+ Because of clock granularity, expiration times may occur up to one
331
+ second sooner than you expect. For example, suppose you store a value
332
+ with a lifetime of ten seconds, and you store it at 12:00:00.998 on a
333
+ certain day. Memoize will look at the clock and see 12:00:00. Then
334
+ 9.01 seconds later, at 12:00:10.008 you try to read it back. Memoize
335
+ will look at the clock and see 12:00:10 and conclude that the value
336
+ has expired. This will probably not occur if you have
337
+ C<Time::HiRes> installed.
338
+
339
+ =head1 AUTHOR
340
+
341
+ Mark-Jason Dominus
342
+
343
+ Mike Cariaso provided valuable insight into the best way to solve this
344
+ problem.
345
+
346
+ =head1 SEE ALSO
347
+
348
+ perl(1)
349
+
350
+ The Memoize man page.
351
+
352
+ =cut
git/usr/share/perl5/core_perl/Memoize/NDBM_File.pm ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ use strict; use warnings;
2
+
3
+ package Memoize::NDBM_File;
4
+ our $VERSION = '1.17';
5
+
6
+ use NDBM_File;
7
+ our @ISA = qw(NDBM_File);
8
+
9
+ # NDBM_File cannot store undef and will store an empty string if you try
10
+ # but it does return undef if you try to read a non-existent key
11
+ # so we can emulate exists() using defined()
12
+ sub EXISTS {
13
+ defined shift->FETCH(@_);
14
+ }
15
+
16
+ # Perl 5.37.3 adds this EXISTS emulation to NDBM_File itself
17
+ delete $Memoize::NDBM_File::{'EXISTS'}
18
+ if eval { NDBM_File->VERSION( '1.16' ) };
19
+
20
+ 1;
21
+
22
+ __END__
23
+
24
+ =pod
25
+
26
+ =head1 NAME
27
+
28
+ Memoize::NDBM_File - glue to provide EXISTS for NDBM_File for Storable use
29
+
30
+ =head1 DESCRIPTION
31
+
32
+ This class provides L<EXISTS|perltie/C<EXISTS>> support for L<NDBM_File>.
33
+
34
+ L<In Perl 5.37.3|https://github.com/Perl/perl5/commit/c0a1a377c02ed789f5eff667f46a2314a05c5a4c>,
35
+ support for C<EXISTS> was added to L<NDBM_File> itself.
36
+ Any code which already requires perl >= 5.37.3 should be rewritten to use
37
+ L<NDBM_File> directly.
38
+
39
+ =cut
git/usr/share/perl5/core_perl/Memoize/SDBM_File.pm ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ use strict; use warnings;
2
+
3
+ package Memoize::SDBM_File;
4
+ our $VERSION = '1.17';
5
+
6
+ use SDBM_File 1.01; # for EXISTS support
7
+ our @ISA = qw(SDBM_File);
8
+
9
+ 1;
10
+
11
+ __END__
12
+
13
+ =pod
14
+
15
+ =head1 NAME
16
+
17
+ Memoize::SDBM_File - DEPRECATED compatibility shim
18
+
19
+ =head1 DESCRIPTION
20
+
21
+ This class used to provide L<EXISTS|perltie/C<EXISTS>> support for L<SDBM_File>
22
+ before support for C<EXISTS> was added to L<SDBM_File> itself
23
+ L<in Perl 5.6.0|perl56delta/SDBM_File>.
24
+
25
+ Any code still using this class should be rewritten to use L<SDBM_File> directly.
26
+
27
+ =cut
git/usr/share/perl5/core_perl/Memoize/Storable.pm ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ use strict; use warnings;
2
+
3
+ package Memoize::Storable;
4
+ our $VERSION = '1.17';
5
+
6
+ use Storable 1.002 (); # for lock_* function variants
7
+
8
+ our $Verbose;
9
+
10
+ sub TIEHASH {
11
+ my $package = shift;
12
+ my $filename = shift;
13
+ my $truehash = (-e $filename) ? Storable::lock_retrieve($filename) : {};
14
+ my %options;
15
+ print STDERR "Memoize::Storable::TIEHASH($filename, @_)\n" if $Verbose;
16
+ @options{@_} = (1) x @_;
17
+ my $self =
18
+ {FILENAME => $filename,
19
+ H => $truehash,
20
+ OPTIONS => \%options
21
+ };
22
+ bless $self => $package;
23
+ }
24
+
25
+ sub STORE {
26
+ my $self = shift;
27
+ print STDERR "Memoize::Storable::STORE(@_)\n" if $Verbose;
28
+ $self->{H}{$_[0]} = $_[1];
29
+ }
30
+
31
+ sub FETCH {
32
+ my $self = shift;
33
+ print STDERR "Memoize::Storable::FETCH(@_)\n" if $Verbose;
34
+ $self->{H}{$_[0]};
35
+ }
36
+
37
+ sub EXISTS {
38
+ my $self = shift;
39
+ print STDERR "Memoize::Storable::EXISTS(@_)\n" if $Verbose;
40
+ exists $self->{H}{$_[0]};
41
+ }
42
+
43
+ sub DESTROY {
44
+ my $self= shift;
45
+ print STDERR "Memoize::Storable::DESTROY(@_)\n" if $Verbose;
46
+ if ($self->{OPTIONS}{'nstore'}) {
47
+ Storable::lock_nstore($self->{H}, $self->{FILENAME});
48
+ } else {
49
+ Storable::lock_store($self->{H}, $self->{FILENAME});
50
+ }
51
+ }
52
+
53
+ sub FIRSTKEY {
54
+ 'Fake hash from Memoize::Storable';
55
+ }
56
+
57
+ sub NEXTKEY {
58
+ undef;
59
+ }
60
+
61
+ 1;
62
+
63
+ __END__
64
+
65
+ =pod
66
+
67
+ =head1 NAME
68
+
69
+ Memoize::Storable - store Memoized data in Storable database
70
+
71
+ =head1 DESCRIPTION
72
+
73
+ See L<Memoize>.
74
+
75
+ =cut
git/usr/share/perl5/core_perl/Module/CoreList.pm ADDED
The diff for this file is too large to render. See raw diff
 
git/usr/share/perl5/core_perl/Module/Load.pm ADDED
@@ -0,0 +1,373 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package Module::Load;
2
+
3
+ use strict;
4
+ use warnings;
5
+ use File::Spec ();
6
+
7
+ our $VERSION = '0.36';
8
+
9
+
10
+ sub import {
11
+ my $who = _who();
12
+ my $h; shift;
13
+
14
+ { no strict 'refs';
15
+
16
+ @_ or (
17
+ *{"${who}::load"} = \&load, # compat to prev version
18
+ *{"${who}::autoload"} = \&autoload,
19
+ return
20
+ );
21
+
22
+ map { $h->{$_} = () if defined $_ } @_;
23
+
24
+ (exists $h->{none} or exists $h->{''})
25
+ and shift, last;
26
+
27
+ ((exists $h->{autoload} and shift,1) or (exists $h->{all} and shift))
28
+ and *{"${who}::autoload"} = \&autoload;
29
+
30
+ ((exists $h->{load} and shift,1) or exists $h->{all})
31
+ and *{"${who}::load"} = \&load;
32
+
33
+ ((exists $h->{load_remote} and shift,1) or exists $h->{all})
34
+ and *{"${who}::load_remote"} = \&load_remote;
35
+
36
+ ((exists $h->{autoload_remote} and shift,1) or exists $h->{all})
37
+ and *{"${who}::autoload_remote"} = \&autoload_remote;
38
+
39
+ }
40
+
41
+ }
42
+
43
+ sub load(*;@){
44
+ goto &_load;
45
+ }
46
+
47
+ sub autoload(*;@){
48
+ unshift @_, 'autoimport';
49
+ goto &_load;
50
+ }
51
+
52
+ sub load_remote($$;@){
53
+ my ($dst, $src, @exp) = @_;
54
+
55
+ eval "package $dst;Module::Load::load('$src', qw/@exp/);";
56
+ $@ && die "$@";
57
+ }
58
+
59
+ sub autoload_remote($$;@){
60
+ my ($dst, $src, @exp) = @_;
61
+
62
+ eval "package $dst;Module::Load::autoload('$src', qw/@exp/);";
63
+ $@ && die "$@";
64
+ }
65
+
66
+ sub _load{
67
+ my $autoimport = $_[0] eq 'autoimport' and shift;
68
+ my $mod = shift or return;
69
+ my $who = _who();
70
+
71
+ if( _is_file( $mod ) ) {
72
+ require $mod;
73
+ } else {
74
+ LOAD: {
75
+ my $err;
76
+ for my $flag ( qw[1 0] ) {
77
+ my $file = _to_file( $mod, $flag);
78
+ eval { require $file };
79
+ $@ ? $err .= $@ : last LOAD;
80
+ }
81
+ die $err if $err;
82
+ }
83
+ }
84
+
85
+ ### This addresses #41883: Module::Load cannot import
86
+ ### non-Exporter module. ->import() routines weren't
87
+ ### properly called when load() was used.
88
+
89
+ { no strict 'refs';
90
+ my $import;
91
+
92
+ ((@_ or $autoimport) and (
93
+ $import = $mod->can('import')
94
+ ) and (
95
+ unshift(@_, $mod),
96
+ goto &$import
97
+ )
98
+ );
99
+ }
100
+
101
+ }
102
+
103
+ sub _to_file{
104
+ local $_ = shift;
105
+ my $pm = shift || '';
106
+
107
+ ## trailing blanks ignored by default. [rt #69886]
108
+ my @parts = split /::|'/, $_, -1;
109
+ ## make sure that we can't hop out of @INC
110
+ shift @parts if @parts && !$parts[0];
111
+
112
+ ### because of [perl #19213], see caveats ###
113
+ my $file = $^O eq 'MSWin32'
114
+ ? join "/", @parts
115
+ : File::Spec->catfile( @parts );
116
+
117
+ $file .= '.pm' if $pm;
118
+
119
+ ### on perl's before 5.10 (5.9.5@31746) if you require
120
+ ### a file in VMS format, it's stored in %INC in VMS
121
+ ### format. Therefor, better unixify it first
122
+ ### Patch in reply to John Malmbergs patch (as mentioned
123
+ ### above) on p5p Tue 21 Aug 2007 04:55:07
124
+ $file = VMS::Filespec::unixify($file) if $^O eq 'VMS';
125
+
126
+ return $file;
127
+ }
128
+
129
+ sub _who { (caller(1))[0] }
130
+
131
+ sub _is_file {
132
+ local $_ = shift;
133
+ return /^\./ ? 1 :
134
+ /[^\w:']/ ? 1 :
135
+ undef
136
+ #' silly bbedit..
137
+ }
138
+
139
+
140
+ 1;
141
+
142
+ __END__
143
+
144
+ =pod
145
+
146
+ =head1 NAME
147
+
148
+ Module::Load - runtime require of both modules and files
149
+
150
+ =head1 SYNOPSIS
151
+
152
+ use Module::Load;
153
+
154
+ my $module = 'Data::Dumper';
155
+
156
+ load Data::Dumper; # loads that module, but not import any functions
157
+ # -> cannot use 'Dumper' function
158
+
159
+ load 'Data::Dumper'; # ditto
160
+ load $module # tritto
161
+
162
+ autoload Data::Dumper; # loads that module and imports the default functions
163
+ # -> can use 'Dumper' function
164
+
165
+ my $script = 'some/script.pl'
166
+ load $script;
167
+ load 'some/script.pl'; # use quotes because of punctuations
168
+
169
+ load thing; # try 'thing' first, then 'thing.pm'
170
+
171
+ load CGI, ':all'; # like 'use CGI qw[:standard]'
172
+
173
+ =head1 DESCRIPTION
174
+
175
+ C<Module::Load> eliminates the need to know whether you are trying
176
+ to require either a file or a module.
177
+
178
+ If you consult C<perldoc -f require> you will see that C<require> will
179
+ behave differently when given a bareword or a string.
180
+
181
+ In the case of a string, C<require> assumes you are wanting to load a
182
+ file. But in the case of a bareword, it assumes you mean a module.
183
+
184
+ This gives nasty overhead when you are trying to dynamically require
185
+ modules at runtime, since you will need to change the module notation
186
+ (C<Acme::Comment>) to a file notation fitting the particular platform
187
+ you are on.
188
+
189
+ C<Module::Load> eliminates the need for this overhead and will
190
+ just DWYM.
191
+
192
+ =head2 Difference between C<load> and C<autoload>
193
+
194
+ C<Module::Load> imports the two functions - C<load> and C<autoload>
195
+
196
+ C<autoload> imports the default functions automatically,
197
+ but C<load> do not import any functions.
198
+
199
+ C<autoload> is usable under C<BEGIN{};>.
200
+
201
+ Both the functions can import the functions that are specified.
202
+
203
+ Following codes are same.
204
+
205
+ load File::Spec::Functions, qw/splitpath/;
206
+
207
+ autoload File::Spec::Functions, qw/splitpath/;
208
+
209
+ =head1 FUNCTIONS
210
+
211
+ =over 4
212
+
213
+ =item load
214
+
215
+ Loads a specified module.
216
+
217
+ See L</Rules> for detailed loading rule.
218
+
219
+ =item autoload
220
+
221
+ Loads a specified module and imports the default functions.
222
+
223
+ Except importing the functions, 'autoload' is same as 'load'.
224
+
225
+ =item load_remote
226
+
227
+ Loads a specified module to the specified package.
228
+
229
+ use Module::Load 'load_remote';
230
+
231
+ my $pkg = 'Other::Package';
232
+
233
+ load_remote $pkg, 'Data::Dumper'; # load a module to 'Other::Package'
234
+ # but do not import 'Dumper' function
235
+
236
+ A module for loading must be quoted.
237
+
238
+ Except specifing the package and quoting module name,
239
+ 'load_remote' is same as 'load'.
240
+
241
+ =item autoload_remote
242
+
243
+ Loads a specified module and imports the default functions to the specified package.
244
+
245
+ use Module::Load 'autoload_remote';
246
+
247
+ my $pkg = 'Other::Package';
248
+
249
+ autoload_remote $pkg, 'Data::Dumper'; # load a module to 'Other::Package'
250
+ # and imports 'Dumper' function
251
+
252
+ A module for loading must be quoted.
253
+
254
+ Except specifing the package and quoting module name,
255
+ 'autoload_remote' is same as 'load_remote'.
256
+
257
+ =back
258
+
259
+ =head1 Rules
260
+
261
+ All functions have the following rules to decide what it thinks
262
+ you want:
263
+
264
+ =over 4
265
+
266
+ =item *
267
+
268
+ If the argument has any characters in it other than those matching
269
+ C<\w>, C<:> or C<'>, it must be a file
270
+
271
+ =item *
272
+
273
+ If the argument matches only C<[\w:']>, it must be a module
274
+
275
+ =item *
276
+
277
+ If the argument matches only C<\w>, it could either be a module or a
278
+ file. We will try to find C<file.pm> first in C<@INC> and if that
279
+ fails, we will try to find C<file> in @INC. If both fail, we die with
280
+ the respective error messages.
281
+
282
+ =back
283
+
284
+ =head1 IMPORTS THE FUNCTIONS
285
+
286
+ 'load' and 'autoload' are imported by default, but 'load_remote' and
287
+ 'autoload_remote' are not imported.
288
+
289
+ To use 'load_remote' or 'autoload_remote', specify at 'use'.
290
+
291
+ =over 4
292
+
293
+ =item "load","autoload","load_remote","autoload_remote"
294
+
295
+ Imports the selected functions.
296
+
297
+ # imports 'load' and 'autoload' (default)
298
+ use Module::Load;
299
+
300
+ # imports 'autoload' only
301
+ use Module::Load 'autoload';
302
+
303
+ # imports 'autoload' and 'autoload_remote', but don't import 'load';
304
+ use Module::Load qw/autoload autoload_remote/;
305
+
306
+ =item 'all'
307
+
308
+ Imports all the functions.
309
+
310
+ use Module::Load 'all'; # imports load, autoload, load_remote, autoload_remote
311
+
312
+ =item '','none',undef
313
+
314
+ Not import any functions (C<load> and C<autoload> are not imported).
315
+
316
+ use Module::Load '';
317
+
318
+ use Module::Load 'none';
319
+
320
+ use Module::Load undef;
321
+
322
+ =back
323
+
324
+ =head1 Caveats
325
+
326
+ Because of a bug in perl (#19213), at least in version 5.6.1, we have
327
+ to hardcode the path separator for a require on Win32 to be C</>, like
328
+ on Unix rather than the Win32 C<\>. Otherwise perl will not read its
329
+ own %INC accurately double load files if they are required again, or
330
+ in the worst case, core dump.
331
+
332
+ C<Module::Load> cannot do implicit imports, only explicit imports.
333
+ (in other words, you always have to specify explicitly what you wish
334
+ to import from a module, even if the functions are in that modules'
335
+ C<@EXPORT>)
336
+
337
+ =head1 SEE ALSO
338
+
339
+ L<Module::Runtime> provides functions for loading modules,
340
+ checking the validity of a module name,
341
+ converting a module name to partial C<.pm> path,
342
+ and related utility functions.
343
+
344
+ L<"require" in perlfunc|https://metacpan.org/pod/perlfunc#require>
345
+ and
346
+ L<"use" in perlfunc|https://metacpan.org/pod/perlfunc#use>.
347
+
348
+ L<Mojo::Loader> is a "class loader and plugin framework",
349
+ and is included in the
350
+ L<Mojolicious|https://metacpan.org/release/Mojolicious> distribution.
351
+
352
+ L<Module::Loader> is a module for finding and loading modules
353
+ in a given namespace, inspired by C<Mojo::Loader>.
354
+
355
+
356
+ =head1 ACKNOWLEDGEMENTS
357
+
358
+ Thanks to Jonas B. Nielsen for making explicit imports work.
359
+
360
+ =head1 BUG REPORTS
361
+
362
+ Please report bugs or other issues to E<lt>bug-module-load@rt.cpan.orgE<gt>.
363
+
364
+ =head1 AUTHOR
365
+
366
+ This module by Jos Boumans E<lt>kane@cpan.orgE<gt>.
367
+
368
+ =head1 COPYRIGHT
369
+
370
+ This library is free software; you may redistribute and/or modify it
371
+ under the same terms as Perl itself.
372
+
373
+ =cut
git/usr/share/perl5/core_perl/Module/Loaded.pm ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package Module::Loaded;
2
+
3
+ use strict;
4
+ use Carp qw[carp];
5
+
6
+ BEGIN { use base 'Exporter';
7
+ use vars qw[@EXPORT $VERSION];
8
+
9
+ $VERSION = '0.08';
10
+ @EXPORT = qw[mark_as_loaded mark_as_unloaded is_loaded];
11
+ }
12
+
13
+ =head1 NAME
14
+
15
+ Module::Loaded - mark modules as loaded or unloaded
16
+
17
+ =head1 SYNOPSIS
18
+
19
+ use Module::Loaded;
20
+
21
+ $bool = mark_as_loaded('Foo'); # Foo.pm is now marked as loaded
22
+ $loc = is_loaded('Foo'); # location of Foo.pm set to the
23
+ # loaders location
24
+ eval "require 'Foo'"; # is now a no-op
25
+
26
+ $bool = mark_as_unloaded('Foo'); # Foo.pm no longer marked as loaded
27
+ eval "require 'Foo'"; # Will try to find Foo.pm in @INC
28
+
29
+ =head1 DESCRIPTION
30
+
31
+ When testing applications, often you find yourself needing to provide
32
+ functionality in your test environment that would usually be provided
33
+ by external modules. Rather than munging the C<%INC> by hand to mark
34
+ these external modules as loaded, so they are not attempted to be loaded
35
+ by perl, this module offers you a very simple way to mark modules as
36
+ loaded and/or unloaded.
37
+
38
+ =head1 FUNCTIONS
39
+
40
+ =head2 $bool = mark_as_loaded( PACKAGE );
41
+
42
+ Marks the package as loaded to perl. C<PACKAGE> can be a bareword or
43
+ string.
44
+
45
+ If the module is already loaded, C<mark_as_loaded> will carp about
46
+ this and tell you from where the C<PACKAGE> has been loaded already.
47
+
48
+ =cut
49
+
50
+ sub mark_as_loaded (*) {
51
+ my $pm = shift;
52
+ my $file = __PACKAGE__->_pm_to_file( $pm ) or return;
53
+ my $who = [caller]->[1];
54
+
55
+ my $where = is_loaded( $pm );
56
+ if ( defined $where ) {
57
+ carp "'$pm' already marked as loaded ('$where')";
58
+
59
+ } else {
60
+ $INC{$file} = $who;
61
+ }
62
+
63
+ return 1;
64
+ }
65
+
66
+ =head2 $bool = mark_as_unloaded( PACKAGE );
67
+
68
+ Marks the package as unloaded to perl, which is the exact opposite
69
+ of C<mark_as_loaded>. C<PACKAGE> can be a bareword or string.
70
+
71
+ If the module is already unloaded, C<mark_as_unloaded> will carp about
72
+ this and tell you the C<PACKAGE> has been unloaded already.
73
+
74
+ =cut
75
+
76
+ sub mark_as_unloaded (*) {
77
+ my $pm = shift;
78
+ my $file = __PACKAGE__->_pm_to_file( $pm ) or return;
79
+
80
+ unless( defined is_loaded( $pm ) ) {
81
+ carp "'$pm' already marked as unloaded";
82
+
83
+ } else {
84
+ delete $INC{ $file };
85
+ }
86
+
87
+ return 1;
88
+ }
89
+
90
+ =head2 $loc = is_loaded( PACKAGE );
91
+
92
+ C<is_loaded> tells you if C<PACKAGE> has been marked as loaded yet.
93
+ C<PACKAGE> can be a bareword or string.
94
+
95
+ It returns falls if C<PACKAGE> has not been loaded yet and the location
96
+ from where it is said to be loaded on success.
97
+
98
+ =cut
99
+
100
+ sub is_loaded (*) {
101
+ my $pm = shift;
102
+ my $file = __PACKAGE__->_pm_to_file( $pm ) or return;
103
+
104
+ return $INC{$file} if exists $INC{$file};
105
+
106
+ return;
107
+ }
108
+
109
+
110
+ sub _pm_to_file {
111
+ my $pkg = shift;
112
+ my $pm = shift or return;
113
+
114
+ my $file = join '/', split '::', $pm;
115
+ $file .= '.pm';
116
+
117
+ return $file;
118
+ }
119
+
120
+ =head1 BUG REPORTS
121
+
122
+ Please report bugs or other issues to E<lt>bug-module-loaded@rt.cpan.org<gt>.
123
+
124
+ =head1 AUTHOR
125
+
126
+ This module by Jos Boumans E<lt>kane@cpan.orgE<gt>.
127
+
128
+ =head1 COPYRIGHT
129
+
130
+ This library is free software; you may redistribute and/or modify it
131
+ under the same terms as Perl itself.
132
+
133
+ =cut
134
+
135
+ # Local variables:
136
+ # c-indentation-style: bsd
137
+ # c-basic-offset: 4
138
+ # indent-tabs-mode: nil
139
+ # End:
140
+ # vim: expandtab shiftwidth=4:
141
+
142
+ 1;
git/usr/share/perl5/core_perl/Module/Metadata.pm ADDED
@@ -0,0 +1,1207 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- mode: cperl; tab-width: 8; indent-tabs-mode: nil; basic-offset: 2 -*-
2
+ # vim:ts=8:sw=2:et:sta:sts=2:tw=78
3
+ package Module::Metadata; # git description: v1.000037-8-g92dec6c
4
+ # ABSTRACT: Gather package and POD information from perl module files
5
+
6
+ # Adapted from Perl-licensed code originally distributed with
7
+ # Module-Build by Ken Williams
8
+
9
+ # This module provides routines to gather information about
10
+ # perl modules (assuming this may be expanded in the distant
11
+ # parrot future to look at other types of modules).
12
+
13
+ sub __clean_eval { eval $_[0] }
14
+ use strict;
15
+ use warnings;
16
+
17
+ our $VERSION = '1.000038';
18
+
19
+ use Carp qw/croak/;
20
+ use File::Spec;
21
+ BEGIN {
22
+ # Try really hard to not depend ony any DynaLoaded module, such as IO::File or Fcntl
23
+ eval {
24
+ require Fcntl; Fcntl->import('SEEK_SET'); 1;
25
+ } or *SEEK_SET = sub { 0 }
26
+ }
27
+ use version 0.87;
28
+ BEGIN {
29
+ if ($INC{'Log/Contextual.pm'}) {
30
+ require "Log/Contextual/WarnLogger.pm"; # Hide from AutoPrereqs
31
+ Log::Contextual->import('log_info',
32
+ '-default_logger' => Log::Contextual::WarnLogger->new({ env_prefix => 'MODULE_METADATA', }),
33
+ );
34
+ }
35
+ else {
36
+ *log_info = sub (&) { warn $_[0]->() };
37
+ }
38
+ }
39
+ use File::Find qw(find);
40
+
41
+ my $V_NUM_REGEXP = qr{v?[0-9._]+}; # crudely, a v-string or decimal
42
+
43
+ my $PKG_FIRST_WORD_REGEXP = qr{ # the FIRST word in a package name
44
+ [a-zA-Z_] # the first word CANNOT start with a digit
45
+ (?:
46
+ [\w']? # can contain letters, digits, _, or ticks
47
+ \w # But, NO multi-ticks or trailing ticks
48
+ )*
49
+ }x;
50
+
51
+ my $PKG_ADDL_WORD_REGEXP = qr{ # the 2nd+ word in a package name
52
+ \w # the 2nd+ word CAN start with digits
53
+ (?:
54
+ [\w']? # and can contain letters or ticks
55
+ \w # But, NO multi-ticks or trailing ticks
56
+ )*
57
+ }x;
58
+
59
+ my $PKG_NAME_REGEXP = qr{ # match a package name
60
+ (?: :: )? # a pkg name can start with arisdottle
61
+ $PKG_FIRST_WORD_REGEXP # a package word
62
+ (?:
63
+ (?: :: )+ ### arisdottle (allow one or many times)
64
+ $PKG_ADDL_WORD_REGEXP ### a package word
65
+ )* # ^ zero, one or many times
66
+ (?:
67
+ :: # allow trailing arisdottle
68
+ )?
69
+ }x;
70
+
71
+ my $PKG_REGEXP = qr{ # match a package declaration
72
+ ^[\s\{;]* # intro chars on a line
73
+ package # the word 'package'
74
+ \s+ # whitespace
75
+ ($PKG_NAME_REGEXP) # a package name
76
+ \s* # optional whitespace
77
+ ($V_NUM_REGEXP)? # optional version number
78
+ \s* # optional whitespace
79
+ [;\{] # semicolon line terminator or block start (since 5.16)
80
+ }x;
81
+
82
+ my $CLASS_REGEXP = qr{ # match a class declaration (core since 5.38)
83
+ ^[\s\{;]* # intro chars on a line
84
+ class # the word 'class'
85
+ \s+ # whitespace
86
+ ($PKG_NAME_REGEXP) # a package name
87
+ \s* # optional whitespace
88
+ ($V_NUM_REGEXP)? # optional version number
89
+ \s* # optional whitespace
90
+ [;\{] # semicolon line terminator or block start
91
+ }x;
92
+
93
+ my $VARNAME_REGEXP = qr{ # match fully-qualified VERSION name
94
+ ([\$*]) # sigil - $ or *
95
+ (
96
+ ( # optional leading package name
97
+ (?:::|\')? # possibly starting like just :: (a la $::VERSION)
98
+ (?:\w+(?:::|\'))* # Foo::Bar:: ...
99
+ )?
100
+ VERSION
101
+ )\b
102
+ }x;
103
+
104
+ my $VERS_REGEXP = qr{ # match a VERSION definition
105
+ (?:
106
+ \(\s*$VARNAME_REGEXP\s*\) # with parens
107
+ |
108
+ $VARNAME_REGEXP # without parens
109
+ )
110
+ \s*
111
+ =[^=~>] # = but not ==, nor =~, nor =>
112
+ }x;
113
+
114
+ sub new_from_file {
115
+ my $class = shift;
116
+ my $filename = File::Spec->rel2abs( shift );
117
+
118
+ return undef unless defined( $filename ) && -f $filename;
119
+ return $class->_init(undef, $filename, @_);
120
+ }
121
+
122
+ sub new_from_handle {
123
+ my $class = shift;
124
+ my $handle = shift;
125
+ my $filename = shift;
126
+ return undef unless defined($handle) && defined($filename);
127
+ $filename = File::Spec->rel2abs( $filename );
128
+
129
+ return $class->_init(undef, $filename, @_, handle => $handle);
130
+
131
+ }
132
+
133
+
134
+ sub new_from_module {
135
+ my $class = shift;
136
+ my $module = shift;
137
+ my %props = @_;
138
+
139
+ $props{inc} ||= \@INC;
140
+ my $filename = $class->find_module_by_name( $module, $props{inc} );
141
+ return undef unless defined( $filename ) && -f $filename;
142
+ return $class->_init($module, $filename, %props);
143
+ }
144
+
145
+ {
146
+
147
+ my $compare_versions = sub {
148
+ my ($v1, $op, $v2) = @_;
149
+ $v1 = version->new($v1)
150
+ unless UNIVERSAL::isa($v1,'version');
151
+
152
+ my $eval_str = "\$v1 $op \$v2";
153
+ my $result = eval $eval_str;
154
+ log_info { "error comparing versions: '$eval_str' $@" } if $@;
155
+
156
+ return $result;
157
+ };
158
+
159
+ my $normalize_version = sub {
160
+ my ($version) = @_;
161
+ if ( $version =~ /[=<>!,]/ ) { # logic, not just version
162
+ # take as is without modification
163
+ }
164
+ elsif ( ref $version eq 'version' ) { # version objects
165
+ $version = $version->is_qv ? $version->normal : $version->stringify;
166
+ }
167
+ elsif ( $version =~ /^[^v][^.]*\.[^.]+\./ ) { # no leading v, multiple dots
168
+ # normalize string tuples without "v": "1.2.3" -> "v1.2.3"
169
+ $version = "v$version";
170
+ }
171
+ else {
172
+ # leave alone
173
+ }
174
+ return $version;
175
+ };
176
+
177
+ # separate out some of the conflict resolution logic
178
+
179
+ my $resolve_module_versions = sub {
180
+ my $packages = shift;
181
+
182
+ my( $file, $version );
183
+ my $err = '';
184
+ foreach my $p ( @$packages ) {
185
+ if ( defined( $p->{version} ) ) {
186
+ if ( defined( $version ) ) {
187
+ if ( $compare_versions->( $version, '!=', $p->{version} ) ) {
188
+ $err .= " $p->{file} ($p->{version})\n";
189
+ }
190
+ else {
191
+ # same version declared multiple times, ignore
192
+ }
193
+ }
194
+ else {
195
+ $file = $p->{file};
196
+ $version = $p->{version};
197
+ }
198
+ }
199
+ $file ||= $p->{file} if defined( $p->{file} );
200
+ }
201
+
202
+ if ( $err ) {
203
+ $err = " $file ($version)\n" . $err;
204
+ }
205
+
206
+ my %result = (
207
+ file => $file,
208
+ version => $version,
209
+ err => $err
210
+ );
211
+
212
+ return \%result;
213
+ };
214
+
215
+ sub provides {
216
+ my $class = shift;
217
+
218
+ croak "provides() requires key/value pairs \n" if @_ % 2;
219
+ my %args = @_;
220
+
221
+ croak "provides() takes only one of 'dir' or 'files'\n"
222
+ if $args{dir} && $args{files};
223
+
224
+ croak "provides() requires a 'version' argument"
225
+ unless defined $args{version};
226
+
227
+ croak "provides() does not support version '$args{version}' metadata"
228
+ unless grep $args{version} eq $_, qw/1.4 2/;
229
+
230
+ $args{prefix} = 'lib' unless defined $args{prefix};
231
+
232
+ my $p;
233
+ if ( $args{dir} ) {
234
+ $p = $class->package_versions_from_directory($args{dir});
235
+ }
236
+ else {
237
+ croak "provides() requires 'files' to be an array reference\n"
238
+ unless ref $args{files} eq 'ARRAY';
239
+ $p = $class->package_versions_from_directory($args{files});
240
+ }
241
+
242
+ # Now, fix up files with prefix
243
+ if ( length $args{prefix} ) { # check in case disabled with q{}
244
+ $args{prefix} =~ s{/$}{};
245
+ for my $v ( values %$p ) {
246
+ $v->{file} = "$args{prefix}/$v->{file}";
247
+ }
248
+ }
249
+
250
+ return $p
251
+ }
252
+
253
+ sub package_versions_from_directory {
254
+ my ( $class, $dir, $files ) = @_;
255
+
256
+ my @files;
257
+
258
+ if ( $files ) {
259
+ @files = @$files;
260
+ }
261
+ else {
262
+ find( {
263
+ wanted => sub {
264
+ push @files, $_ if -f $_ && /\.pm$/;
265
+ },
266
+ no_chdir => 1,
267
+ }, $dir );
268
+ }
269
+
270
+ # First, we enumerate all packages & versions,
271
+ # separating into primary & alternative candidates
272
+ my( %prime, %alt );
273
+ foreach my $file (@files) {
274
+ my $mapped_filename = File::Spec->abs2rel( $file, $dir );
275
+ my @path = File::Spec->splitdir( $mapped_filename );
276
+ (my $prime_package = join( '::', @path )) =~ s/\.pm$//;
277
+
278
+ my $pm_info = $class->new_from_file( $file );
279
+
280
+ foreach my $package ( $pm_info->packages_inside ) {
281
+ next if $package eq 'main'; # main can appear numerous times, ignore
282
+ next if $package eq 'DB'; # special debugging package, ignore
283
+ next if grep /^_/, split( /::/, $package ); # private package, ignore
284
+
285
+ my $version = $pm_info->version( $package );
286
+
287
+ $prime_package = $package if lc($prime_package) eq lc($package);
288
+ if ( $package eq $prime_package ) {
289
+ if ( exists( $prime{$package} ) ) {
290
+ croak "Unexpected conflict in '$package'; multiple versions found.\n";
291
+ }
292
+ else {
293
+ $mapped_filename = "$package.pm" if lc("$package.pm") eq lc($mapped_filename);
294
+ $prime{$package}{file} = $mapped_filename;
295
+ $prime{$package}{version} = $version if defined( $version );
296
+ }
297
+ }
298
+ else {
299
+ push( @{$alt{$package}}, {
300
+ file => $mapped_filename,
301
+ version => $version,
302
+ } );
303
+ }
304
+ }
305
+ }
306
+
307
+ # Then we iterate over all the packages found above, identifying conflicts
308
+ # and selecting the "best" candidate for recording the file & version
309
+ # for each package.
310
+ foreach my $package ( keys( %alt ) ) {
311
+ my $result = $resolve_module_versions->( $alt{$package} );
312
+
313
+ if ( exists( $prime{$package} ) ) { # primary package selected
314
+
315
+ if ( $result->{err} ) {
316
+ # Use the selected primary package, but there are conflicting
317
+ # errors among multiple alternative packages that need to be
318
+ # reported
319
+ log_info {
320
+ "Found conflicting versions for package '$package'\n" .
321
+ " $prime{$package}{file} ($prime{$package}{version})\n" .
322
+ $result->{err}
323
+ };
324
+
325
+ }
326
+ elsif ( defined( $result->{version} ) ) {
327
+ # There is a primary package selected, and exactly one
328
+ # alternative package
329
+
330
+ if ( exists( $prime{$package}{version} ) &&
331
+ defined( $prime{$package}{version} ) ) {
332
+ # Unless the version of the primary package agrees with the
333
+ # version of the alternative package, report a conflict
334
+ if ( $compare_versions->(
335
+ $prime{$package}{version}, '!=', $result->{version}
336
+ )
337
+ ) {
338
+
339
+ log_info {
340
+ "Found conflicting versions for package '$package'\n" .
341
+ " $prime{$package}{file} ($prime{$package}{version})\n" .
342
+ " $result->{file} ($result->{version})\n"
343
+ };
344
+ }
345
+
346
+ }
347
+ else {
348
+ # The prime package selected has no version so, we choose to
349
+ # use any alternative package that does have a version
350
+ $prime{$package}{file} = $result->{file};
351
+ $prime{$package}{version} = $result->{version};
352
+ }
353
+
354
+ }
355
+ else {
356
+ # no alt package found with a version, but we have a prime
357
+ # package so we use it whether it has a version or not
358
+ }
359
+
360
+ }
361
+ else { # No primary package was selected, use the best alternative
362
+
363
+ if ( $result->{err} ) {
364
+ log_info {
365
+ "Found conflicting versions for package '$package'\n" .
366
+ $result->{err}
367
+ };
368
+ }
369
+
370
+ # Despite possible conflicting versions, we choose to record
371
+ # something rather than nothing
372
+ $prime{$package}{file} = $result->{file};
373
+ $prime{$package}{version} = $result->{version}
374
+ if defined( $result->{version} );
375
+ }
376
+ }
377
+
378
+ # Normalize versions. Can't use exists() here because of bug in YAML::Node.
379
+ # XXX "bug in YAML::Node" comment seems irrelevant -- dagolden, 2009-05-18
380
+ for (grep defined $_->{version}, values %prime) {
381
+ $_->{version} = $normalize_version->( $_->{version} );
382
+ }
383
+
384
+ return \%prime;
385
+ }
386
+ }
387
+
388
+
389
+ sub _init {
390
+ my $class = shift;
391
+ my $module = shift;
392
+ my $filename = shift;
393
+ my %props = @_;
394
+
395
+ my $handle = delete $props{handle};
396
+ my( %valid_props, @valid_props );
397
+ @valid_props = qw( collect_pod inc decode_pod );
398
+ @valid_props{@valid_props} = delete( @props{@valid_props} );
399
+ warn "Unknown properties: @{[keys %props]}\n" if scalar( %props );
400
+
401
+ my %data = (
402
+ module => $module,
403
+ filename => $filename,
404
+ version => undef,
405
+ packages => [],
406
+ versions => {},
407
+ pod => {},
408
+ pod_headings => [],
409
+ collect_pod => 0,
410
+
411
+ %valid_props,
412
+ );
413
+
414
+ my $self = bless(\%data, $class);
415
+
416
+ if ( not $handle ) {
417
+ my $filename = $self->{filename};
418
+ open $handle, '<', $filename
419
+ or croak( "Can't open '$filename': $!" );
420
+
421
+ $self->_handle_bom($handle, $filename);
422
+ }
423
+ $self->_parse_fh($handle);
424
+
425
+ @{$self->{packages}} = __uniq(@{$self->{packages}});
426
+
427
+ unless($self->{module} and length($self->{module})) {
428
+ # CAVEAT (possible TODO): .pmc files not treated the same as .pm
429
+ if ($self->{filename} =~ /\.pm$/) {
430
+ my ($v, $d, $f) = File::Spec->splitpath($self->{filename});
431
+ $f =~ s/\..+$//;
432
+ my @candidates = grep /(^|::)$f$/, @{$self->{packages}};
433
+ $self->{module} = shift(@candidates); # this may be undef
434
+ }
435
+ else {
436
+ # this seems like an atrocious heuristic, albeit marginally better than
437
+ # what was here before. It should be rewritten entirely to be more like
438
+ # "if it's not a .pm file, it's not require()able as a name, therefore
439
+ # name() should be undef."
440
+ if ((grep /main/, @{$self->{packages}})
441
+ or (grep /main/, keys %{$self->{versions}})) {
442
+ $self->{module} = 'main';
443
+ }
444
+ else {
445
+ # TODO: this should maybe default to undef instead
446
+ $self->{module} = $self->{packages}[0] || '';
447
+ }
448
+ }
449
+ }
450
+
451
+ $self->{version} = $self->{versions}{$self->{module}}
452
+ if defined( $self->{module} );
453
+
454
+ return $self;
455
+ }
456
+
457
+ # class method
458
+ sub _do_find_module {
459
+ my $class = shift;
460
+ my $module = shift || croak 'find_module_by_name() requires a package name';
461
+ my $dirs = shift || \@INC;
462
+
463
+ my $file = File::Spec->catfile(split( /::/, $module));
464
+ foreach my $dir ( @$dirs ) {
465
+ my $testfile = File::Spec->catfile($dir, $file);
466
+ return [ File::Spec->rel2abs( $testfile ), $dir ]
467
+ if -e $testfile and !-d _; # For stuff like ExtUtils::xsubpp
468
+ # CAVEAT (possible TODO): .pmc files are not discoverable here
469
+ $testfile .= '.pm';
470
+ return [ File::Spec->rel2abs( $testfile ), $dir ]
471
+ if -e $testfile;
472
+ }
473
+ return;
474
+ }
475
+
476
+ # class method
477
+ sub find_module_by_name {
478
+ my $found = shift()->_do_find_module(@_) or return;
479
+ return $found->[0];
480
+ }
481
+
482
+ # class method
483
+ sub find_module_dir_by_name {
484
+ my $found = shift()->_do_find_module(@_) or return;
485
+ return $found->[1];
486
+ }
487
+
488
+
489
+ # given a line of perl code, attempt to parse it if it looks like a
490
+ # $VERSION assignment, returning sigil, full name, & package name
491
+ sub _parse_version_expression {
492
+ my $self = shift;
493
+ my $line = shift;
494
+
495
+ my( $sigil, $variable_name, $package);
496
+ if ( $line =~ /$VERS_REGEXP/o ) {
497
+ ( $sigil, $variable_name, $package) = $2 ? ( $1, $2, $3 ) : ( $4, $5, $6 );
498
+ if ( $package ) {
499
+ $package = ($package eq '::') ? 'main' : $package;
500
+ $package =~ s/::$//;
501
+ }
502
+ }
503
+
504
+ return ( $sigil, $variable_name, $package );
505
+ }
506
+
507
+ # Look for a UTF-8/UTF-16BE/UTF-16LE BOM at the beginning of the stream.
508
+ # If there's one, then skip it and set the :encoding layer appropriately.
509
+ sub _handle_bom {
510
+ my ($self, $fh, $filename) = @_;
511
+
512
+ my $pos = tell $fh;
513
+ return unless defined $pos;
514
+
515
+ my $buf = ' ' x 2;
516
+ my $count = read $fh, $buf, length $buf;
517
+ return unless defined $count and $count >= 2;
518
+
519
+ my $encoding;
520
+ if ( $buf eq "\x{FE}\x{FF}" ) {
521
+ $encoding = 'UTF-16BE';
522
+ }
523
+ elsif ( $buf eq "\x{FF}\x{FE}" ) {
524
+ $encoding = 'UTF-16LE';
525
+ }
526
+ elsif ( $buf eq "\x{EF}\x{BB}" ) {
527
+ $buf = ' ';
528
+ $count = read $fh, $buf, length $buf;
529
+ if ( defined $count and $count >= 1 and $buf eq "\x{BF}" ) {
530
+ $encoding = 'UTF-8';
531
+ }
532
+ }
533
+
534
+ if ( defined $encoding ) {
535
+ if ( "$]" >= 5.008 ) {
536
+ binmode( $fh, ":encoding($encoding)" );
537
+ }
538
+ }
539
+ else {
540
+ seek $fh, $pos, SEEK_SET
541
+ or croak( sprintf "Can't reset position to the top of '$filename'" );
542
+ }
543
+
544
+ return $encoding;
545
+ }
546
+
547
+ sub _parse_fh {
548
+ my ($self, $fh) = @_;
549
+
550
+ my( $in_pod, $seen_end, $need_vers ) = ( 0, 0, 0 );
551
+ my( @packages, %vers, %pod, @pod );
552
+ my $package = 'main';
553
+ my $pod_sect = '';
554
+ my $pod_data = '';
555
+ my $in_end = 0;
556
+ my $encoding = '';
557
+
558
+ while (defined( my $line = <$fh> )) {
559
+ my $line_num = $.;
560
+
561
+ chomp( $line );
562
+
563
+ # From toke.c : any line that begins by "=X", where X is an alphabetic
564
+ # character, introduces a POD segment.
565
+ my $is_cut;
566
+ if ( $line =~ /^=([a-zA-Z].*)/ ) {
567
+ my $cmd = $1;
568
+ # Then it goes back to Perl code for "=cutX" where X is a non-alphabetic
569
+ # character (which includes the newline, but here we chomped it away).
570
+ $is_cut = $cmd =~ /^cut(?:[^a-zA-Z]|$)/;
571
+ $in_pod = !$is_cut;
572
+ }
573
+
574
+ if ( $in_pod ) {
575
+
576
+ if ( $line =~ /^=head[1-4]\s+(.+)\s*$/ ) {
577
+ push( @pod, $1 );
578
+ if ( $self->{collect_pod} && length( $pod_data ) ) {
579
+ $pod{$pod_sect} = $pod_data;
580
+ $pod_data = '';
581
+ }
582
+ $pod_sect = $1;
583
+ }
584
+ elsif ( $self->{collect_pod} ) {
585
+ if ( $self->{decode_pod} && $line =~ /^=encoding ([\w-]+)/ ) {
586
+ $encoding = $1;
587
+ }
588
+ $pod_data .= "$line\n";
589
+ }
590
+ next;
591
+ }
592
+ elsif ( $is_cut ) {
593
+ if ( $self->{collect_pod} && length( $pod_data ) ) {
594
+ $pod{$pod_sect} = $pod_data;
595
+ $pod_data = '';
596
+ }
597
+ $pod_sect = '';
598
+ next;
599
+ }
600
+
601
+ # Skip after __END__
602
+ next if $in_end;
603
+
604
+ # Skip comments in code
605
+ next if $line =~ /^\s*#/;
606
+
607
+ # Would be nice if we could also check $in_string or something too
608
+ if ($line eq '__END__') {
609
+ $in_end++;
610
+ next;
611
+ }
612
+
613
+ last if $line eq '__DATA__';
614
+
615
+ # parse $line to see if it's a $VERSION declaration
616
+ my( $version_sigil, $version_fullname, $version_package ) =
617
+ index($line, 'VERSION') >= 1
618
+ ? $self->_parse_version_expression( $line )
619
+ : ();
620
+
621
+ if ( $line =~ /$PKG_REGEXP/o or $line =~ /$CLASS_REGEXP/ ) {
622
+ $package = $1;
623
+ my $version = $2;
624
+ push( @packages, $package ) unless grep( $package eq $_, @packages );
625
+ $need_vers = defined $version ? 0 : 1;
626
+
627
+ if ( not exists $vers{$package} and defined $version ){
628
+ # Upgrade to a version object.
629
+ my $dwim_version = eval { _dwim_version($version) };
630
+ croak "Version '$version' from $self->{filename} does not appear to be valid:\n$line\n\nThe fatal error was: $@\n"
631
+ unless defined $dwim_version; # "0" is OK!
632
+ $vers{$package} = $dwim_version;
633
+ }
634
+ }
635
+
636
+ # VERSION defined with full package spec, i.e. $Module::VERSION
637
+ elsif ( $version_fullname && $version_package ) {
638
+ # we do NOT save this package in found @packages
639
+ $need_vers = 0 if $version_package eq $package;
640
+
641
+ unless ( defined $vers{$version_package} && length $vers{$version_package} ) {
642
+ $vers{$version_package} = $self->_evaluate_version_line( $version_sigil, $version_fullname, $line );
643
+ }
644
+ }
645
+
646
+ # first non-comment line in undeclared package main is VERSION
647
+ elsif ( $package eq 'main' && $version_fullname && !exists($vers{main}) ) {
648
+ $need_vers = 0;
649
+ my $v = $self->_evaluate_version_line( $version_sigil, $version_fullname, $line );
650
+ $vers{$package} = $v;
651
+ push( @packages, 'main' );
652
+ }
653
+
654
+ # first non-comment line in undeclared package defines package main
655
+ elsif ( $package eq 'main' && !exists($vers{main}) && $line =~ /\w/ ) {
656
+ $need_vers = 1;
657
+ $vers{main} = '';
658
+ push( @packages, 'main' );
659
+ }
660
+
661
+ # only keep if this is the first $VERSION seen
662
+ elsif ( $version_fullname && $need_vers ) {
663
+ $need_vers = 0;
664
+ my $v = $self->_evaluate_version_line( $version_sigil, $version_fullname, $line );
665
+
666
+ unless ( defined $vers{$package} && length $vers{$package} ) {
667
+ $vers{$package} = $v;
668
+ }
669
+ }
670
+ } # end loop over each line
671
+
672
+ if ( $self->{collect_pod} && length($pod_data) ) {
673
+ $pod{$pod_sect} = $pod_data;
674
+ }
675
+
676
+ if ( $self->{decode_pod} && $encoding ) {
677
+ require Encode;
678
+ $_ = Encode::decode( $encoding, $_ ) for values %pod;
679
+ }
680
+
681
+ $self->{versions} = \%vers;
682
+ $self->{packages} = \@packages;
683
+ $self->{pod} = \%pod;
684
+ $self->{pod_headings} = \@pod;
685
+ }
686
+
687
+ sub __uniq (@)
688
+ {
689
+ my (%seen, $key);
690
+ grep !$seen{ $key = $_ }++, @_;
691
+ }
692
+
693
+ {
694
+ my $pn = 0;
695
+ sub _evaluate_version_line {
696
+ my $self = shift;
697
+ my( $sigil, $variable_name, $line ) = @_;
698
+
699
+ # We compile into a local sub because 'use version' would cause
700
+ # compiletime/runtime issues with local()
701
+ $pn++; # everybody gets their own package
702
+ my $eval = qq{ my \$dummy = q# Hide from _packages_inside()
703
+ #; package Module::Metadata::_version::p${pn};
704
+ use version;
705
+ sub {
706
+ local $sigil$variable_name;
707
+ $line;
708
+ return \$$variable_name if defined \$$variable_name;
709
+ return \$Module::Metadata::_version::p${pn}::$variable_name;
710
+ };
711
+ };
712
+
713
+ $eval = $1 if $eval =~ m{^(.+)}s;
714
+
715
+ local $^W;
716
+ # Try to get the $VERSION
717
+ my $vsub = __clean_eval($eval);
718
+ # some modules say $VERSION <equal sign> $Foo::Bar::VERSION, but Foo::Bar isn't
719
+ # installed, so we need to hunt in ./lib for it
720
+ if ( $@ =~ /Can't locate/ && -d 'lib' ) {
721
+ local @INC = ('lib',@INC);
722
+ $vsub = __clean_eval($eval);
723
+ }
724
+ warn "Error evaling version line '$eval' in $self->{filename}: $@\n"
725
+ if $@;
726
+
727
+ (ref($vsub) eq 'CODE') or
728
+ croak "failed to build version sub for $self->{filename}";
729
+
730
+ my $result = eval { $vsub->() };
731
+ # FIXME: $eval is not the right thing to print here
732
+ croak "Could not get version from $self->{filename} by executing:\n$eval\n\nThe fatal error was: $@\n"
733
+ if $@;
734
+
735
+ # Upgrade it into a version object
736
+ my $version = eval { _dwim_version($result) };
737
+
738
+ # FIXME: $eval is not the right thing to print here
739
+ croak "Version '$result' from $self->{filename} does not appear to be valid:\n$eval\n\nThe fatal error was: $@\n"
740
+ unless defined $version; # "0" is OK!
741
+
742
+ return $version;
743
+ }
744
+ }
745
+
746
+ # Try to DWIM when things fail the lax version test in obvious ways
747
+ {
748
+ my @version_prep = (
749
+ # Best case, it just works
750
+ sub { return shift },
751
+
752
+ # If we still don't have a version, try stripping any
753
+ # trailing junk that is prohibited by lax rules
754
+ sub {
755
+ my $v = shift;
756
+ $v =~ s{([0-9])[a-z-].*$}{$1}i; # 1.23-alpha or 1.23b
757
+ return $v;
758
+ },
759
+
760
+ # Activestate apparently creates custom versions like '1.23_45_01', which
761
+ # cause version.pm to think it's an invalid alpha. So check for that
762
+ # and strip them
763
+ sub {
764
+ my $v = shift;
765
+ my $num_dots = () = $v =~ m{(\.)}g;
766
+ my $num_unders = () = $v =~ m{(_)}g;
767
+ my $leading_v = substr($v,0,1) eq 'v';
768
+ if ( ! $leading_v && $num_dots < 2 && $num_unders > 1 ) {
769
+ $v =~ s{_}{}g;
770
+ $num_unders = () = $v =~ m{(_)}g;
771
+ }
772
+ return $v;
773
+ },
774
+
775
+ # Worst case, try numifying it like we would have before version objects
776
+ sub {
777
+ my $v = shift;
778
+ no warnings 'numeric';
779
+ return 0 + $v;
780
+ },
781
+
782
+ );
783
+
784
+ sub _dwim_version {
785
+ my ($result) = shift;
786
+
787
+ return $result if ref($result) eq 'version';
788
+
789
+ my ($version, $error);
790
+ for my $f (@version_prep) {
791
+ $result = $f->($result);
792
+ $version = eval { version->new($result) };
793
+ $error ||= $@ if $@; # capture first failure
794
+ last if defined $version;
795
+ }
796
+
797
+ croak $error unless defined $version;
798
+
799
+ return $version;
800
+ }
801
+ }
802
+
803
+ ############################################################
804
+
805
+ # accessors
806
+ sub name { $_[0]->{module} }
807
+
808
+ sub filename { $_[0]->{filename} }
809
+ sub packages_inside { @{$_[0]->{packages}} }
810
+ sub pod_inside { @{$_[0]->{pod_headings}} }
811
+ sub contains_pod { 0+@{$_[0]->{pod_headings}} }
812
+
813
+ sub version {
814
+ my $self = shift;
815
+ my $mod = shift || $self->{module};
816
+ my $vers;
817
+ if ( defined( $mod ) && length( $mod ) &&
818
+ exists( $self->{versions}{$mod} ) ) {
819
+ return $self->{versions}{$mod};
820
+ }
821
+ else {
822
+ return undef;
823
+ }
824
+ }
825
+
826
+ sub pod {
827
+ my $self = shift;
828
+ my $sect = shift;
829
+ if ( defined( $sect ) && length( $sect ) &&
830
+ exists( $self->{pod}{$sect} ) ) {
831
+ return $self->{pod}{$sect};
832
+ }
833
+ else {
834
+ return undef;
835
+ }
836
+ }
837
+
838
+ sub is_indexable {
839
+ my ($self, $package) = @_;
840
+
841
+ my @indexable_packages = grep $_ ne 'main', $self->packages_inside;
842
+
843
+ # check for specific package, if provided
844
+ return !! grep $_ eq $package, @indexable_packages if $package;
845
+
846
+ # otherwise, check for any indexable packages at all
847
+ return !! @indexable_packages;
848
+ }
849
+
850
+ 1;
851
+
852
+ __END__
853
+
854
+ =pod
855
+
856
+ =encoding UTF-8
857
+
858
+ =head1 NAME
859
+
860
+ Module::Metadata - Gather package and POD information from perl module files
861
+
862
+ =head1 VERSION
863
+
864
+ version 1.000038
865
+
866
+ =head1 SYNOPSIS
867
+
868
+ use Module::Metadata;
869
+
870
+ # information about a .pm file
871
+ my $info = Module::Metadata->new_from_file( $file );
872
+ my $version = $info->version;
873
+
874
+ # CPAN META 'provides' field for .pm files in a directory
875
+ my $provides = Module::Metadata->provides(
876
+ dir => 'lib', version => 2
877
+ );
878
+
879
+ =head1 DESCRIPTION
880
+
881
+ This module provides a standard way to gather metadata about a .pm file through
882
+ (mostly) static analysis and (some) code execution. When determining the
883
+ version of a module, the C<$VERSION> assignment is C<eval>ed, as is traditional
884
+ in the CPAN toolchain.
885
+
886
+ =head1 CLASS METHODS
887
+
888
+ =head2 C<< new_from_file($filename, collect_pod => 1, decode_pod => 1) >>
889
+
890
+ Constructs a C<Module::Metadata> object given the path to a file. Returns
891
+ undef if the filename does not exist.
892
+
893
+ C<collect_pod> is a optional boolean argument that determines whether POD
894
+ data is collected and stored for reference. POD data is not collected by
895
+ default. POD headings are always collected.
896
+
897
+ If the file begins by an UTF-8, UTF-16BE or UTF-16LE byte-order mark, then
898
+ it is skipped before processing, and the content of the file is also decoded
899
+ appropriately starting from perl 5.8.
900
+
901
+ Alternatively, if C<decode_pod> is set, it will decode the collected pod
902
+ sections according to the C<=encoding> declaration.
903
+
904
+ =head2 C<< new_from_handle($handle, $filename, collect_pod => 1, decode_pod => 1) >>
905
+
906
+ This works just like C<new_from_file>, except that a handle can be provided
907
+ as the first argument.
908
+
909
+ Note that there is no validation to confirm that the handle is a handle or
910
+ something that can act like one. Passing something that isn't a handle will
911
+ cause a exception when trying to read from it. The C<filename> argument is
912
+ mandatory or undef will be returned.
913
+
914
+ You are responsible for setting the decoding layers on C<$handle> if
915
+ required.
916
+
917
+ =head2 C<< new_from_module($module, collect_pod => 1, inc => \@dirs, decode_pod => 1) >>
918
+
919
+ Constructs a C<Module::Metadata> object given a module or package name.
920
+ Returns undef if the module cannot be found.
921
+
922
+ In addition to accepting the C<collect_pod> and C<decode_pod> arguments as
923
+ described above, this method accepts a C<inc> argument which is a reference to
924
+ an array of directories to search for the module. If none are given, the
925
+ default is @INC.
926
+
927
+ If the file that contains the module begins by an UTF-8, UTF-16BE or
928
+ UTF-16LE byte-order mark, then it is skipped before processing, and the
929
+ content of the file is also decoded appropriately starting from perl 5.8.
930
+
931
+ =head2 C<< find_module_by_name($module, \@dirs) >>
932
+
933
+ Returns the path to a module given the module or package name. A list
934
+ of directories can be passed in as an optional parameter, otherwise
935
+ @INC is searched.
936
+
937
+ Can be called as either an object or a class method.
938
+
939
+ =head2 C<< find_module_dir_by_name($module, \@dirs) >>
940
+
941
+ Returns the entry in C<@dirs> (or C<@INC> by default) that contains
942
+ the module C<$module>. A list of directories can be passed in as an
943
+ optional parameter, otherwise @INC is searched.
944
+
945
+ Can be called as either an object or a class method.
946
+
947
+ =head2 C<< provides( %options ) >>
948
+
949
+ This is a convenience wrapper around C<package_versions_from_directory>
950
+ to generate a CPAN META C<provides> data structure. It takes key/value
951
+ pairs. Valid option keys include:
952
+
953
+ =over
954
+
955
+ =item version B<(required)>
956
+
957
+ Specifies which version of the L<CPAN::Meta::Spec> should be used as
958
+ the format of the C<provides> output. Currently only '1.4' and '2'
959
+ are supported (and their format is identical). This may change in
960
+ the future as the definition of C<provides> changes.
961
+
962
+ The C<version> option is required. If it is omitted or if
963
+ an unsupported version is given, then C<provides> will throw an error.
964
+
965
+ =item dir
966
+
967
+ Directory to search recursively for F<.pm> files. May not be specified with
968
+ C<files>.
969
+
970
+ =item files
971
+
972
+ Array reference of files to examine. May not be specified with C<dir>.
973
+
974
+ =item prefix
975
+
976
+ String to prepend to the C<file> field of the resulting output. This defaults
977
+ to F<lib>, which is the common case for most CPAN distributions with their
978
+ F<.pm> files in F<lib>. This option ensures the META information has the
979
+ correct relative path even when the C<dir> or C<files> arguments are
980
+ absolute or have relative paths from a location other than the distribution
981
+ root.
982
+
983
+ =back
984
+
985
+ For example, given C<dir> of 'lib' and C<prefix> of 'lib', the return value
986
+ is a hashref of the form:
987
+
988
+ {
989
+ 'Package::Name' => {
990
+ version => '0.123',
991
+ file => 'lib/Package/Name.pm'
992
+ },
993
+ 'OtherPackage::Name' => ...
994
+ }
995
+
996
+ =head2 C<< package_versions_from_directory($dir, \@files?) >>
997
+
998
+ Scans C<$dir> for .pm files (unless C<@files> is given, in which case looks
999
+ for those files in C<$dir> - and reads each file for packages and versions,
1000
+ returning a hashref of the form:
1001
+
1002
+ {
1003
+ 'Package::Name' => {
1004
+ version => '0.123',
1005
+ file => 'Package/Name.pm'
1006
+ },
1007
+ 'OtherPackage::Name' => ...
1008
+ }
1009
+
1010
+ The C<DB> and C<main> packages are always omitted, as are any "private"
1011
+ packages that have leading underscores in the namespace (e.g.
1012
+ C<Foo::_private>)
1013
+
1014
+ Note that the file path is relative to C<$dir> if that is specified.
1015
+ This B<must not> be used directly for CPAN META C<provides>. See
1016
+ the C<provides> method instead.
1017
+
1018
+ =head2 C<< log_info (internal) >>
1019
+
1020
+ Used internally to perform logging; imported from Log::Contextual if
1021
+ Log::Contextual has already been loaded, otherwise simply calls warn.
1022
+
1023
+ =head1 OBJECT METHODS
1024
+
1025
+ =head2 C<< name() >>
1026
+
1027
+ Returns the name of the package represented by this module. If there
1028
+ is more than one package, it makes a best guess based on the
1029
+ filename. If it's a script (i.e. not a *.pm) the package name is
1030
+ 'main'.
1031
+
1032
+ =head2 C<< version($package) >>
1033
+
1034
+ Returns the version as defined by the $VERSION variable for the
1035
+ package as returned by the C<name> method if no arguments are
1036
+ given. If given the name of a package it will attempt to return the
1037
+ version of that package if it is specified in the file.
1038
+
1039
+ =head2 C<< filename() >>
1040
+
1041
+ Returns the absolute path to the file.
1042
+ Note that this file may not actually exist on disk yet, e.g. if the module was read from an in-memory filehandle.
1043
+
1044
+ =head2 C<< packages_inside() >>
1045
+
1046
+ Returns a list of packages. Note: this is a raw list of packages
1047
+ discovered (or assumed, in the case of C<main>). It is not
1048
+ filtered for C<DB>, C<main> or private packages the way the
1049
+ C<provides> method does. Invalid package names are not returned,
1050
+ for example "Foo:Bar". Strange but valid package names are
1051
+ returned, for example "Foo::Bar::", and are left up to the caller
1052
+ on how to handle.
1053
+
1054
+ =head2 C<< pod_inside() >>
1055
+
1056
+ Returns a list of POD sections.
1057
+
1058
+ =head2 C<< contains_pod() >>
1059
+
1060
+ Returns true if there is any POD in the file.
1061
+
1062
+ =head2 C<< pod($section) >>
1063
+
1064
+ Returns the POD data in the given section.
1065
+
1066
+ =head2 C<< is_indexable($package) >> or C<< is_indexable() >>
1067
+
1068
+ Available since version 1.000020.
1069
+
1070
+ Returns a boolean indicating whether the package (if provided) or any package
1071
+ (otherwise) is eligible for indexing by PAUSE, the Perl Authors Upload Server.
1072
+ Note This only checks for valid C<package> declarations, and does not take any
1073
+ ownership information into account.
1074
+
1075
+ =head1 SUPPORT
1076
+
1077
+ Bugs may be submitted through L<the RT bug tracker|https://rt.cpan.org/Public/Dist/Display.html?Name=Module-Metadata>
1078
+ (or L<bug-Module-Metadata@rt.cpan.org|mailto:bug-Module-Metadata@rt.cpan.org>).
1079
+
1080
+ There is also a mailing list available for users of this distribution, at
1081
+ L<http://lists.perl.org/list/cpan-workers.html>.
1082
+
1083
+ There is also an irc channel available for users of this distribution, at
1084
+ L<C<#toolchain> on C<irc.perl.org>|irc://irc.perl.org/#toolchain>.
1085
+
1086
+ =head1 AUTHOR
1087
+
1088
+ Original code from Module::Build::ModuleInfo by Ken Williams
1089
+ <kwilliams@cpan.org>, Randy W. Sims <RandyS@ThePierianSpring.org>
1090
+
1091
+ Released as Module::Metadata by Matt S Trout (mst) <mst@shadowcat.co.uk> with
1092
+ assistance from David Golden (xdg) <dagolden@cpan.org>.
1093
+
1094
+ =head1 CONTRIBUTORS
1095
+
1096
+ =for stopwords Karen Etheridge David Golden Vincent Pit Matt S Trout Chris Nehren Graham Knop Olivier Mengué Tomas Doran Christian Walde Craig A. Berry Tatsuhiko Miyagawa tokuhirom 'BinGOs' Williams Mitchell Steinbrunner Edward Zborowski Gareth Harper James Raspass Jerry D. Hedden Josh Jore Kent Fredric Leon Timmermans Peter Rabbitson Steve Hay
1097
+
1098
+ =over 4
1099
+
1100
+ =item *
1101
+
1102
+ Karen Etheridge <ether@cpan.org>
1103
+
1104
+ =item *
1105
+
1106
+ David Golden <dagolden@cpan.org>
1107
+
1108
+ =item *
1109
+
1110
+ Vincent Pit <perl@profvince.com>
1111
+
1112
+ =item *
1113
+
1114
+ Matt S Trout <mst@shadowcat.co.uk>
1115
+
1116
+ =item *
1117
+
1118
+ Chris Nehren <apeiron@cpan.org>
1119
+
1120
+ =item *
1121
+
1122
+ Graham Knop <haarg@haarg.org>
1123
+
1124
+ =item *
1125
+
1126
+ Olivier Mengué <dolmen@cpan.org>
1127
+
1128
+ =item *
1129
+
1130
+ Tomas Doran <bobtfish@bobtfish.net>
1131
+
1132
+ =item *
1133
+
1134
+ Christian Walde <walde.christian@googlemail.com>
1135
+
1136
+ =item *
1137
+
1138
+ Craig A. Berry <cberry@cpan.org>
1139
+
1140
+ =item *
1141
+
1142
+ Tatsuhiko Miyagawa <miyagawa@bulknews.net>
1143
+
1144
+ =item *
1145
+
1146
+ tokuhirom <tokuhirom@gmail.com>
1147
+
1148
+ =item *
1149
+
1150
+ Chris 'BinGOs' Williams <chris@bingosnet.co.uk>
1151
+
1152
+ =item *
1153
+
1154
+ David Mitchell <davem@iabyn.com>
1155
+
1156
+ =item *
1157
+
1158
+ David Steinbrunner <dsteinbrunner@pobox.com>
1159
+
1160
+ =item *
1161
+
1162
+ Edward Zborowski <ed@rubensteintech.com>
1163
+
1164
+ =item *
1165
+
1166
+ Gareth Harper <gareth@broadbean.com>
1167
+
1168
+ =item *
1169
+
1170
+ James Raspass <jraspass@gmail.com>
1171
+
1172
+ =item *
1173
+
1174
+ Jerry D. Hedden <jdhedden@cpan.org>
1175
+
1176
+ =item *
1177
+
1178
+ Josh Jore <jjore@cpan.org>
1179
+
1180
+ =item *
1181
+
1182
+ Kent Fredric <kentnl@cpan.org>
1183
+
1184
+ =item *
1185
+
1186
+ Leon Timmermans <fawaka@gmail.com>
1187
+
1188
+ =item *
1189
+
1190
+ Peter Rabbitson <ribasushi@cpan.org>
1191
+
1192
+ =item *
1193
+
1194
+ Steve Hay <steve.m.hay@googlemail.com>
1195
+
1196
+ =back
1197
+
1198
+ =head1 COPYRIGHT & LICENSE
1199
+
1200
+ Original code Copyright (c) 2001-2011 Ken Williams.
1201
+ Additional code Copyright (c) 2010-2011 Matt Trout and David Golden.
1202
+ All rights reserved.
1203
+
1204
+ This library is free software; you can redistribute it and/or
1205
+ modify it under the same terms as Perl itself.
1206
+
1207
+ =cut
git/usr/share/perl5/core_perl/Net/Cmd.pm ADDED
@@ -0,0 +1,910 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Net::Cmd.pm
2
+ #
3
+ # Copyright (C) 1995-2006 Graham Barr. All rights reserved.
4
+ # Copyright (C) 2013-2016, 2020, 2022 Steve Hay. All rights reserved.
5
+ # This module is free software; you can redistribute it and/or modify it under
6
+ # the same terms as Perl itself, i.e. under the terms of either the GNU General
7
+ # Public License or the Artistic License, as specified in the F<LICENCE> file.
8
+
9
+ package Net::Cmd;
10
+
11
+ use 5.008001;
12
+
13
+ use strict;
14
+ use warnings;
15
+
16
+ use Carp;
17
+ use Exporter;
18
+ use Symbol 'gensym';
19
+ use Errno 'EINTR';
20
+
21
+ BEGIN {
22
+ if (ord "A" == 193) {
23
+ require Convert::EBCDIC;
24
+
25
+ # Convert::EBCDIC->import;
26
+ }
27
+ }
28
+
29
+ our $VERSION = "3.15";
30
+ our @ISA = qw(Exporter);
31
+ our @EXPORT = qw(CMD_INFO CMD_OK CMD_MORE CMD_REJECT CMD_ERROR CMD_PENDING);
32
+
33
+ use constant CMD_INFO => 1;
34
+ use constant CMD_OK => 2;
35
+ use constant CMD_MORE => 3;
36
+ use constant CMD_REJECT => 4;
37
+ use constant CMD_ERROR => 5;
38
+ use constant CMD_PENDING => 0;
39
+
40
+ use constant DEF_REPLY_CODE => 421;
41
+
42
+ my %debug = ();
43
+
44
+ my $tr = ord "A" == 193 ? Convert::EBCDIC->new() : undef;
45
+
46
+ sub toebcdic {
47
+ my $cmd = shift;
48
+
49
+ unless (exists ${*$cmd}{'net_cmd_asciipeer'}) {
50
+ my $string = $_[0];
51
+ my $ebcdicstr = $tr->toebcdic($string);
52
+ ${*$cmd}{'net_cmd_asciipeer'} = $string !~ /^\d+/ && $ebcdicstr =~ /^\d+/;
53
+ }
54
+
55
+ ${*$cmd}{'net_cmd_asciipeer'}
56
+ ? $tr->toebcdic($_[0])
57
+ : $_[0];
58
+ }
59
+
60
+
61
+ sub toascii {
62
+ my $cmd = shift;
63
+ ${*$cmd}{'net_cmd_asciipeer'}
64
+ ? $tr->toascii($_[0])
65
+ : $_[0];
66
+ }
67
+
68
+
69
+ sub _print_isa {
70
+ no strict 'refs'; ## no critic (TestingAndDebugging::ProhibitNoStrict)
71
+
72
+ my $pkg = shift;
73
+ my $cmd = $pkg;
74
+
75
+ $debug{$pkg} ||= 0;
76
+
77
+ my %done = ();
78
+ my @do = ($pkg);
79
+ my %spc = ($pkg, "");
80
+
81
+ while ($pkg = shift @do) {
82
+ next if defined $done{$pkg};
83
+
84
+ $done{$pkg} = 1;
85
+
86
+ my $v =
87
+ defined ${"${pkg}::VERSION"}
88
+ ? "(" . ${"${pkg}::VERSION"} . ")"
89
+ : "";
90
+
91
+ my $spc = $spc{$pkg};
92
+ $cmd->debug_print(1, "${spc}${pkg}${v}\n");
93
+
94
+ if (@{"${pkg}::ISA"}) {
95
+ @spc{@{"${pkg}::ISA"}} = (" " . $spc{$pkg}) x @{"${pkg}::ISA"};
96
+ unshift(@do, @{"${pkg}::ISA"});
97
+ }
98
+ }
99
+ }
100
+
101
+
102
+ sub debug {
103
+ @_ == 1 or @_ == 2 or croak 'usage: $obj->debug([$level])';
104
+
105
+ my ($cmd, $level) = @_;
106
+ my $pkg = ref($cmd) || $cmd;
107
+ my $oldval = 0;
108
+
109
+ if (ref($cmd)) {
110
+ $oldval = ${*$cmd}{'net_cmd_debug'} || 0;
111
+ }
112
+ else {
113
+ $oldval = $debug{$pkg} || 0;
114
+ }
115
+
116
+ return $oldval
117
+ unless @_ == 2;
118
+
119
+ $level = $debug{$pkg} || 0
120
+ unless defined $level;
121
+
122
+ _print_isa($pkg)
123
+ if ($level && !exists $debug{$pkg});
124
+
125
+ if (ref($cmd)) {
126
+ ${*$cmd}{'net_cmd_debug'} = $level;
127
+ }
128
+ else {
129
+ $debug{$pkg} = $level;
130
+ }
131
+
132
+ $oldval;
133
+ }
134
+
135
+
136
+ sub message {
137
+ @_ == 1 or croak 'usage: $obj->message()';
138
+
139
+ my $cmd = shift;
140
+
141
+ wantarray
142
+ ? @{${*$cmd}{'net_cmd_resp'}}
143
+ : join("", @{${*$cmd}{'net_cmd_resp'}});
144
+ }
145
+
146
+
147
+ sub debug_text { $_[2] }
148
+
149
+
150
+ sub debug_print {
151
+ my ($cmd, $out, $text) = @_;
152
+ print STDERR $cmd, ($out ? '>>> ' : '<<< '), $cmd->debug_text($out, $text);
153
+ }
154
+
155
+
156
+ sub code {
157
+ @_ == 1 or croak 'usage: $obj->code()';
158
+
159
+ my $cmd = shift;
160
+
161
+ ${*$cmd}{'net_cmd_code'} = $cmd->DEF_REPLY_CODE
162
+ unless exists ${*$cmd}{'net_cmd_code'};
163
+
164
+ ${*$cmd}{'net_cmd_code'};
165
+ }
166
+
167
+
168
+ sub status {
169
+ @_ == 1 or croak 'usage: $obj->status()';
170
+
171
+ my $cmd = shift;
172
+
173
+ substr(${*$cmd}{'net_cmd_code'}, 0, 1);
174
+ }
175
+
176
+
177
+ sub set_status {
178
+ @_ == 3 or croak 'usage: $obj->set_status($code, $resp)';
179
+
180
+ my $cmd = shift;
181
+ my ($code, $resp) = @_;
182
+
183
+ $resp = defined $resp ? [$resp] : []
184
+ unless ref($resp);
185
+
186
+ (${*$cmd}{'net_cmd_code'}, ${*$cmd}{'net_cmd_resp'}) = ($code, $resp);
187
+
188
+ 1;
189
+ }
190
+
191
+ sub _syswrite_with_timeout {
192
+ my $cmd = shift;
193
+ my $line = shift;
194
+
195
+ my $len = length($line);
196
+ my $offset = 0;
197
+ my $win = "";
198
+ vec($win, fileno($cmd), 1) = 1;
199
+ my $timeout = $cmd->timeout || undef;
200
+ my $initial = time;
201
+ my $pending = $timeout;
202
+
203
+ local $SIG{PIPE} = 'IGNORE' unless $^O eq 'MacOS';
204
+
205
+ while ($len) {
206
+ my $wout;
207
+ my $nfound = select(undef, $wout = $win, undef, $pending);
208
+ if ((defined $nfound and $nfound > 0) or -f $cmd) # -f for testing on win32
209
+ {
210
+ my $w = syswrite($cmd, $line, $len, $offset);
211
+ if (! defined($w) ) {
212
+ my $err = $!;
213
+ $cmd->close;
214
+ $cmd->_set_status_closed($err);
215
+ return;
216
+ }
217
+ $len -= $w;
218
+ $offset += $w;
219
+ }
220
+ elsif ($nfound == -1) {
221
+ if ( $! == EINTR ) {
222
+ if ( defined($timeout) ) {
223
+ redo if ($pending = $timeout - ( time - $initial ) ) > 0;
224
+ $cmd->_set_status_timeout;
225
+ return;
226
+ }
227
+ redo;
228
+ }
229
+ my $err = $!;
230
+ $cmd->close;
231
+ $cmd->_set_status_closed($err);
232
+ return;
233
+ }
234
+ else {
235
+ $cmd->_set_status_timeout;
236
+ return;
237
+ }
238
+ }
239
+
240
+ return 1;
241
+ }
242
+
243
+ sub _set_status_timeout {
244
+ my $cmd = shift;
245
+ my $pkg = ref($cmd) || $cmd;
246
+
247
+ $cmd->set_status($cmd->DEF_REPLY_CODE, "[$pkg] Timeout");
248
+ carp(ref($cmd) . ": " . (caller(1))[3] . "(): timeout") if $cmd->debug;
249
+ }
250
+
251
+ sub _set_status_closed {
252
+ my $cmd = shift;
253
+ my $err = shift;
254
+ my $pkg = ref($cmd) || $cmd;
255
+
256
+ $cmd->set_status($cmd->DEF_REPLY_CODE, "[$pkg] Connection closed");
257
+ carp(ref($cmd) . ": " . (caller(1))[3]
258
+ . "(): unexpected EOF on command channel: $err") if $cmd->debug;
259
+ }
260
+
261
+ sub _is_closed {
262
+ my $cmd = shift;
263
+ if (!defined fileno($cmd)) {
264
+ $cmd->_set_status_closed($!);
265
+ return 1;
266
+ }
267
+ return 0;
268
+ }
269
+
270
+ sub command {
271
+ my $cmd = shift;
272
+
273
+ return $cmd
274
+ if $cmd->_is_closed;
275
+
276
+ $cmd->dataend()
277
+ if (exists ${*$cmd}{'net_cmd_last_ch'});
278
+
279
+ if (scalar(@_)) {
280
+ my $str = join(
281
+ " ",
282
+ map {
283
+ /\n/
284
+ ? do { my $n = $_; $n =~ tr/\n/ /; $n }
285
+ : $_;
286
+ } @_
287
+ );
288
+ $str = $cmd->toascii($str) if $tr;
289
+ $str .= "\015\012";
290
+
291
+ $cmd->debug_print(1, $str)
292
+ if ($cmd->debug);
293
+
294
+ # though documented to return undef on failure, the legacy behavior
295
+ # was to return $cmd even on failure, so this odd construct does that
296
+ $cmd->_syswrite_with_timeout($str)
297
+ or return $cmd;
298
+ }
299
+
300
+ $cmd;
301
+ }
302
+
303
+
304
+ sub ok {
305
+ @_ == 1 or croak 'usage: $obj->ok()';
306
+
307
+ my $code = $_[0]->code;
308
+ 0 < $code && $code < 400;
309
+ }
310
+
311
+
312
+ sub unsupported {
313
+ my $cmd = shift;
314
+
315
+ $cmd->set_status(580, 'Unsupported command');
316
+
317
+ 0;
318
+ }
319
+
320
+
321
+ sub getline {
322
+ my $cmd = shift;
323
+
324
+ ${*$cmd}{'net_cmd_lines'} ||= [];
325
+
326
+ return shift @{${*$cmd}{'net_cmd_lines'}}
327
+ if scalar(@{${*$cmd}{'net_cmd_lines'}});
328
+
329
+ my $partial = defined(${*$cmd}{'net_cmd_partial'}) ? ${*$cmd}{'net_cmd_partial'} : "";
330
+
331
+ return
332
+ if $cmd->_is_closed;
333
+
334
+ my $fd = fileno($cmd);
335
+ my $rin = "";
336
+ vec($rin, $fd, 1) = 1;
337
+
338
+ my $buf;
339
+
340
+ until (scalar(@{${*$cmd}{'net_cmd_lines'}})) {
341
+ my $timeout = $cmd->timeout || undef;
342
+ my $rout;
343
+
344
+ my $select_ret = select($rout = $rin, undef, undef, $timeout);
345
+ if ($select_ret > 0) {
346
+ unless (sysread($cmd, $buf = "", 1024)) {
347
+ my $err = $!;
348
+ $cmd->close;
349
+ $cmd->_set_status_closed($err);
350
+ return;
351
+ }
352
+
353
+ substr($buf, 0, 0) = $partial; ## prepend from last sysread
354
+
355
+ my @buf = split(/\015?\012/, $buf, -1); ## break into lines
356
+
357
+ $partial = pop @buf;
358
+
359
+ push(@{${*$cmd}{'net_cmd_lines'}}, map {"$_\n"} @buf);
360
+
361
+ }
362
+ else {
363
+ $cmd->_set_status_timeout;
364
+ return;
365
+ }
366
+ }
367
+
368
+ ${*$cmd}{'net_cmd_partial'} = $partial;
369
+
370
+ if ($tr) {
371
+ foreach my $ln (@{${*$cmd}{'net_cmd_lines'}}) {
372
+ $ln = $cmd->toebcdic($ln);
373
+ }
374
+ }
375
+
376
+ shift @{${*$cmd}{'net_cmd_lines'}};
377
+ }
378
+
379
+
380
+ sub ungetline {
381
+ my ($cmd, $str) = @_;
382
+
383
+ ${*$cmd}{'net_cmd_lines'} ||= [];
384
+ unshift(@{${*$cmd}{'net_cmd_lines'}}, $str);
385
+ }
386
+
387
+
388
+ sub parse_response {
389
+ return ()
390
+ unless $_[1] =~ s/^(\d\d\d)(.?)//o;
391
+ ($1, $2 eq "-");
392
+ }
393
+
394
+
395
+ sub response {
396
+ my $cmd = shift;
397
+ my ($code, $more) = (undef) x 2;
398
+
399
+ $cmd->set_status($cmd->DEF_REPLY_CODE, undef); # initialize the response
400
+
401
+ while (1) {
402
+ my $str = $cmd->getline();
403
+
404
+ return CMD_ERROR
405
+ unless defined($str);
406
+
407
+ $cmd->debug_print(0, $str)
408
+ if ($cmd->debug);
409
+
410
+ ($code, $more) = $cmd->parse_response($str);
411
+ unless (defined $code) {
412
+ carp("$cmd: response(): parse error in '$str'") if ($cmd->debug);
413
+ $cmd->ungetline($str);
414
+ $@ = $str; # $@ used as tunneling hack
415
+ return CMD_ERROR;
416
+ }
417
+
418
+ ${*$cmd}{'net_cmd_code'} = $code;
419
+
420
+ push(@{${*$cmd}{'net_cmd_resp'}}, $str);
421
+
422
+ last unless ($more);
423
+ }
424
+
425
+ return unless defined $code;
426
+ substr($code, 0, 1);
427
+ }
428
+
429
+
430
+ sub read_until_dot {
431
+ my $cmd = shift;
432
+ my $fh = shift;
433
+ my $arr = [];
434
+
435
+ while (1) {
436
+ my $str = $cmd->getline() or return;
437
+
438
+ $cmd->debug_print(0, $str)
439
+ if ($cmd->debug & 4);
440
+
441
+ last if ($str =~ /^\.\r?\n/o);
442
+
443
+ $str =~ s/^\.\././o;
444
+
445
+ if (defined $fh) {
446
+ print $fh $str;
447
+ }
448
+ else {
449
+ push(@$arr, $str);
450
+ }
451
+ }
452
+
453
+ $arr;
454
+ }
455
+
456
+
457
+ sub datasend {
458
+ my $cmd = shift;
459
+ my $arr = @_ == 1 && ref($_[0]) ? $_[0] : \@_;
460
+ my $line = join("", @$arr);
461
+
462
+ # Perls < 5.10.1 (with the exception of 5.8.9) have a performance problem with
463
+ # the substitutions below when dealing with strings stored internally in
464
+ # UTF-8, so downgrade them (if possible).
465
+ # Data passed to datasend() should be encoded to octets upstream already so
466
+ # shouldn't even have the UTF-8 flag on to start with, but if it so happens
467
+ # that the octets are stored in an upgraded string (as can sometimes occur)
468
+ # then they would still downgrade without fail anyway.
469
+ # Only Unicode codepoints > 0xFF stored in an upgraded string will fail to
470
+ # downgrade. We fail silently in that case, and a "Wide character in print"
471
+ # warning will be emitted later by syswrite().
472
+ utf8::downgrade($line, 1) if $] < 5.010001 && $] != 5.008009;
473
+
474
+ return 0
475
+ if $cmd->_is_closed;
476
+
477
+ my $last_ch = ${*$cmd}{'net_cmd_last_ch'};
478
+
479
+ # We have not send anything yet, so last_ch = "\012" means we are at the start of a line
480
+ $last_ch = ${*$cmd}{'net_cmd_last_ch'} = "\012" unless defined $last_ch;
481
+
482
+ return 1 unless length $line;
483
+
484
+ if ($cmd->debug) {
485
+ foreach my $b (split(/\n/, $line)) {
486
+ $cmd->debug_print(1, "$b\n");
487
+ }
488
+ }
489
+
490
+ $line =~ tr/\r\n/\015\012/ unless "\r" eq "\015";
491
+
492
+ my $first_ch = '';
493
+
494
+ if ($last_ch eq "\015") {
495
+ # Remove \012 so it does not get prefixed with another \015 below
496
+ # and escape the . if there is one following it because the fixup
497
+ # below will not find it
498
+ $first_ch = "\012" if $line =~ s/^\012(\.?)/$1$1/;
499
+ }
500
+ elsif ($last_ch eq "\012") {
501
+ # Fixup below will not find the . as the first character of the buffer
502
+ $first_ch = "." if $line =~ /^\./;
503
+ }
504
+
505
+ $line =~ s/\015?\012(\.?)/\015\012$1$1/sg;
506
+
507
+ substr($line, 0, 0) = $first_ch;
508
+
509
+ ${*$cmd}{'net_cmd_last_ch'} = substr($line, -1, 1);
510
+
511
+ $cmd->_syswrite_with_timeout($line)
512
+ or return;
513
+
514
+ 1;
515
+ }
516
+
517
+
518
+ sub rawdatasend {
519
+ my $cmd = shift;
520
+ my $arr = @_ == 1 && ref($_[0]) ? $_[0] : \@_;
521
+ my $line = join("", @$arr);
522
+
523
+ return 0
524
+ if $cmd->_is_closed;
525
+
526
+ return 1
527
+ unless length($line);
528
+
529
+ if ($cmd->debug) {
530
+ my $b = "$cmd>>> ";
531
+ print STDERR $b, join("\n$b", split(/\n/, $line)), "\n";
532
+ }
533
+
534
+ $cmd->_syswrite_with_timeout($line)
535
+ or return;
536
+
537
+ 1;
538
+ }
539
+
540
+
541
+ sub dataend {
542
+ my $cmd = shift;
543
+
544
+ return 0
545
+ if $cmd->_is_closed;
546
+
547
+ my $ch = ${*$cmd}{'net_cmd_last_ch'};
548
+ my $tosend;
549
+
550
+ if (!defined $ch) {
551
+ return 1;
552
+ }
553
+ elsif ($ch ne "\012") {
554
+ $tosend = "\015\012";
555
+ }
556
+
557
+ $tosend .= ".\015\012";
558
+
559
+ $cmd->debug_print(1, ".\n")
560
+ if ($cmd->debug);
561
+
562
+ $cmd->_syswrite_with_timeout($tosend)
563
+ or return 0;
564
+
565
+ delete ${*$cmd}{'net_cmd_last_ch'};
566
+
567
+ $cmd->response() == CMD_OK;
568
+ }
569
+
570
+ # read and write to tied filehandle
571
+ sub tied_fh {
572
+ my $cmd = shift;
573
+ ${*$cmd}{'net_cmd_readbuf'} = '';
574
+ my $fh = gensym();
575
+ tie *$fh, ref($cmd), $cmd;
576
+ return $fh;
577
+ }
578
+
579
+ # tie to myself
580
+ sub TIEHANDLE {
581
+ my $class = shift;
582
+ my $cmd = shift;
583
+ return $cmd;
584
+ }
585
+
586
+ # Tied filehandle read. Reads requested data length, returning
587
+ # end-of-file when the dot is encountered.
588
+ sub READ {
589
+ my $cmd = shift;
590
+ my ($len, $offset) = @_[1, 2];
591
+ return unless exists ${*$cmd}{'net_cmd_readbuf'};
592
+ my $done = 0;
593
+ while (!$done and length(${*$cmd}{'net_cmd_readbuf'}) < $len) {
594
+ ${*$cmd}{'net_cmd_readbuf'} .= $cmd->getline() or return;
595
+ $done++ if ${*$cmd}{'net_cmd_readbuf'} =~ s/^\.\r?\n\Z//m;
596
+ }
597
+
598
+ $_[0] = '';
599
+ substr($_[0], $offset + 0) = substr(${*$cmd}{'net_cmd_readbuf'}, 0, $len);
600
+ substr(${*$cmd}{'net_cmd_readbuf'}, 0, $len) = '';
601
+ delete ${*$cmd}{'net_cmd_readbuf'} if $done;
602
+
603
+ return length $_[0];
604
+ }
605
+
606
+
607
+ sub READLINE {
608
+ my $cmd = shift;
609
+
610
+ # in this context, we use the presence of readbuf to
611
+ # indicate that we have not yet reached the eof
612
+ return unless exists ${*$cmd}{'net_cmd_readbuf'};
613
+ my $line = $cmd->getline;
614
+ return if $line =~ /^\.\r?\n/;
615
+ $line;
616
+ }
617
+
618
+
619
+ sub PRINT {
620
+ my $cmd = shift;
621
+ my ($buf, $len, $offset) = @_;
622
+ $len ||= length($buf);
623
+ $offset += 0;
624
+ return unless $cmd->datasend(substr($buf, $offset, $len));
625
+ ${*$cmd}{'net_cmd_sending'}++; # flag that we should call dataend()
626
+ return $len;
627
+ }
628
+
629
+
630
+ sub CLOSE {
631
+ my $cmd = shift;
632
+ my $r = exists(${*$cmd}{'net_cmd_sending'}) ? $cmd->dataend : 1;
633
+ delete ${*$cmd}{'net_cmd_readbuf'};
634
+ delete ${*$cmd}{'net_cmd_sending'};
635
+ $r;
636
+ }
637
+
638
+ 1;
639
+
640
+ __END__
641
+
642
+
643
+ =head1 NAME
644
+
645
+ Net::Cmd - Network Command class (as used by FTP, SMTP etc)
646
+
647
+ =head1 SYNOPSIS
648
+
649
+ use Net::Cmd;
650
+
651
+ @ISA = qw(Net::Cmd);
652
+
653
+ =head1 DESCRIPTION
654
+
655
+ C<Net::Cmd> is a collection of methods that can be inherited by a sub-class
656
+ of C<IO::Socket::INET>. These methods implement the functionality required for a
657
+ command based protocol, for example FTP and SMTP.
658
+
659
+ If your sub-class does not also derive from C<IO::Socket::INET> or similar (e.g.
660
+ C<IO::Socket::IP>, C<IO::Socket::INET6> or C<IO::Socket::SSL>) then you must
661
+ provide the following methods by other means yourself: C<close()> and
662
+ C<timeout()>.
663
+
664
+ =head2 Public Methods
665
+
666
+ These methods provide a user interface to the C<Net::Cmd> object.
667
+
668
+ =over 4
669
+
670
+ =item C<debug($level)>
671
+
672
+ Set the level of debug information for this object. If C<$level> is not given
673
+ then the current state is returned. Otherwise the state is changed to
674
+ C<$level> and the previous state returned.
675
+
676
+ Different packages
677
+ may implement different levels of debug but a non-zero value results in
678
+ copies of all commands and responses also being sent to STDERR.
679
+
680
+ If C<$level> is C<undef> then the debug level will be set to the default
681
+ debug level for the class.
682
+
683
+ This method can also be called as a I<static> method to set/get the default
684
+ debug level for a given class.
685
+
686
+ =item C<message()>
687
+
688
+ Returns the text message returned from the last command. In a scalar
689
+ context it returns a single string, in a list context it will return
690
+ each line as a separate element. (See L<PSEUDO RESPONSES> below.)
691
+
692
+ =item C<code()>
693
+
694
+ Returns the 3-digit code from the last command. If a command is pending
695
+ then the value 0 is returned. (See L<PSEUDO RESPONSES> below.)
696
+
697
+ =item C<ok()>
698
+
699
+ Returns non-zero if the last code value was greater than zero and
700
+ less than 400. This holds true for most command servers. Servers
701
+ where this does not hold may override this method.
702
+
703
+ =item C<status()>
704
+
705
+ Returns the most significant digit of the current status code. If a command
706
+ is pending then C<CMD_PENDING> is returned.
707
+
708
+ =item C<datasend($data)>
709
+
710
+ Send data to the remote server, converting LF to CRLF. Any line starting
711
+ with a '.' will be prefixed with another '.'.
712
+ C<$data> may be an array or a reference to an array.
713
+ The C<$data> passed in must be encoded by the caller to octets of whatever
714
+ encoding is required, e.g. by using the Encode module's C<encode()> function.
715
+
716
+ =item C<dataend()>
717
+
718
+ End the sending of data to the remote server. This is done by ensuring that
719
+ the data already sent ends with CRLF then sending '.CRLF' to end the
720
+ transmission. Once this data has been sent C<dataend> calls C<response> and
721
+ returns true if C<response> returns CMD_OK.
722
+
723
+ =back
724
+
725
+ =head2 Protected Methods
726
+
727
+ These methods are not intended to be called by the user, but used or
728
+ over-ridden by a sub-class of C<Net::Cmd>
729
+
730
+ =over 4
731
+
732
+ =item C<debug_print($dir, $text)>
733
+
734
+ Print debugging information. C<$dir> denotes the direction I<true> being
735
+ data being sent to the server. Calls C<debug_text> before printing to
736
+ STDERR.
737
+
738
+ =item C<debug_text($dir, $text)>
739
+
740
+ This method is called to print debugging information. C<$text> is
741
+ the text being sent. The method should return the text to be printed.
742
+
743
+ This is primarily meant for the use of modules such as FTP where passwords
744
+ are sent, but we do not want to display them in the debugging information.
745
+
746
+ =item C<command($cmd[, $args, ... ])>
747
+
748
+ Send a command to the command server. All arguments are first joined with
749
+ a space character and CRLF is appended, this string is then sent to the
750
+ command server.
751
+
752
+ Returns undef upon failure.
753
+
754
+ =item C<unsupported()>
755
+
756
+ Sets the status code to 580 and the response text to 'Unsupported command'.
757
+ Returns zero.
758
+
759
+ =item C<response()>
760
+
761
+ Obtain a response from the server. Upon success the most significant digit
762
+ of the status code is returned. Upon failure, timeout etc., I<CMD_ERROR> is
763
+ returned.
764
+
765
+ =item C<parse_response($text)>
766
+
767
+ This method is called by C<response> as a method with one argument. It should
768
+ return an array of 2 values, the 3-digit status code and a flag which is true
769
+ when this is part of a multi-line response and this line is not the last.
770
+
771
+ =item C<getline()>
772
+
773
+ Retrieve one line, delimited by CRLF, from the remote server. Returns I<undef>
774
+ upon failure.
775
+
776
+ B<NOTE>: If you do use this method for any reason, please remember to add
777
+ some C<debug_print> calls into your method.
778
+
779
+ =item C<ungetline($text)>
780
+
781
+ Unget a line of text from the server.
782
+
783
+ =item C<rawdatasend($data)>
784
+
785
+ Send data to the remote server without performing any conversions. C<$data>
786
+ is a scalar.
787
+ As with C<datasend()>, the C<$data> passed in must be encoded by the caller
788
+ to octets of whatever encoding is required, e.g. by using the Encode module's
789
+ C<encode()> function.
790
+
791
+ =item C<read_until_dot()>
792
+
793
+ Read data from the remote server until a line consisting of a single '.'.
794
+ Any lines starting with '..' will have one of the '.'s removed.
795
+
796
+ Returns a reference to a list containing the lines, or I<undef> upon failure.
797
+
798
+ =item C<tied_fh()>
799
+
800
+ Returns a filehandle tied to the Net::Cmd object. After issuing a
801
+ command, you may read from this filehandle using read() or <>. The
802
+ filehandle will return EOF when the final dot is encountered.
803
+ Similarly, you may write to the filehandle in order to send data to
804
+ the server after issuing a command that expects data to be written.
805
+
806
+ See the Net::POP3 and Net::SMTP modules for examples of this.
807
+
808
+ =back
809
+
810
+ =head2 Pseudo Responses
811
+
812
+ Normally the values returned by C<message()> and C<code()> are
813
+ obtained from the remote server, but in a few circumstances, as
814
+ detailed below, C<Net::Cmd> will return values that it sets. You
815
+ can alter this behavior by overriding DEF_REPLY_CODE() to specify
816
+ a different default reply code, or overriding one of the specific
817
+ error handling methods below.
818
+
819
+ =over 4
820
+
821
+ =item Initial value
822
+
823
+ Before any command has executed or if an unexpected error occurs
824
+ C<code()> will return "421" (temporary connection failure) and
825
+ C<message()> will return undef.
826
+
827
+ =item Connection closed
828
+
829
+ If the underlying C<IO::Handle> is closed, or if there are
830
+ any read or write failures, the file handle will be forced closed,
831
+ and C<code()> will return "421" (temporary connection failure)
832
+ and C<message()> will return "[$pkg] Connection closed"
833
+ (where $pkg is the name of the class that subclassed C<Net::Cmd>).
834
+ The _set_status_closed() method can be overridden to set a different
835
+ message (by calling set_status()) or otherwise trap this error.
836
+
837
+ =item Timeout
838
+
839
+ If there is a read or write timeout C<code()> will return "421"
840
+ (temporary connection failure) and C<message()> will return
841
+ "[$pkg] Timeout" (where $pkg is the name of the class
842
+ that subclassed C<Net::Cmd>). The _set_status_timeout() method
843
+ can be overridden to set a different message (by calling set_status())
844
+ or otherwise trap this error.
845
+
846
+ =back
847
+
848
+ =head1 EXPORTS
849
+
850
+ The following symbols are, or can be, exported by this module:
851
+
852
+ =over 4
853
+
854
+ =item Default Exports
855
+
856
+ C<CMD_INFO>,
857
+ C<CMD_OK>,
858
+ C<CMD_MORE>,
859
+ C<CMD_REJECT>,
860
+ C<CMD_ERROR>,
861
+ C<CMD_PENDING>.
862
+
863
+ (These correspond to possible results of C<response()> and C<status()>.)
864
+
865
+ =item Optional Exports
866
+
867
+ I<None>.
868
+
869
+ =item Export Tags
870
+
871
+ I<None>.
872
+
873
+ =back
874
+
875
+ =head1 KNOWN BUGS
876
+
877
+ See L<https://rt.cpan.org/Dist/Display.html?Status=Active&Queue=libnet>.
878
+
879
+ =head1 AUTHOR
880
+
881
+ Graham Barr E<lt>L<gbarr@pobox.com|mailto:gbarr@pobox.com>E<gt>.
882
+
883
+ Steve Hay E<lt>L<shay@cpan.org|mailto:shay@cpan.org>E<gt> is now maintaining
884
+ libnet as of version 1.22_02.
885
+
886
+ =head1 COPYRIGHT
887
+
888
+ Copyright (C) 1995-2006 Graham Barr. All rights reserved.
889
+
890
+ Copyright (C) 2013-2016, 2020, 2022 Steve Hay. All rights reserved.
891
+
892
+ =head1 LICENCE
893
+
894
+ This module is free software; you can redistribute it and/or modify it under the
895
+ same terms as Perl itself, i.e. under the terms of either the GNU General Public
896
+ License or the Artistic License, as specified in the F<LICENCE> file.
897
+
898
+ =head1 VERSION
899
+
900
+ Version 3.15
901
+
902
+ =head1 DATE
903
+
904
+ 20 March 2023
905
+
906
+ =head1 HISTORY
907
+
908
+ See the F<Changes> file.
909
+
910
+ =cut
git/usr/share/perl5/core_perl/Net/Config.pm ADDED
@@ -0,0 +1,381 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Net::Config.pm
2
+ #
3
+ # Copyright (C) 2000 Graham Barr. All rights reserved.
4
+ # Copyright (C) 2013-2014, 2016, 2020 Steve Hay. All rights reserved.
5
+ # This module is free software; you can redistribute it and/or modify it under
6
+ # the same terms as Perl itself, i.e. under the terms of either the GNU General
7
+ # Public License or the Artistic License, as specified in the F<LICENCE> file.
8
+
9
+ package Net::Config;
10
+
11
+ use 5.008001;
12
+
13
+ use strict;
14
+ use warnings;
15
+
16
+ use Exporter;
17
+ use Socket qw(inet_aton inet_ntoa);
18
+
19
+ our @EXPORT = qw(%NetConfig);
20
+ our @ISA = qw(Net::LocalCfg Exporter);
21
+ our $VERSION = "3.15";
22
+
23
+ our($CONFIGURE, $LIBNET_CFG);
24
+
25
+ eval {
26
+ local @INC = @INC;
27
+ pop @INC if $INC[-1] eq '.';
28
+ local $SIG{__DIE__};
29
+ require Net::LocalCfg;
30
+ };
31
+
32
+ our %NetConfig = (
33
+ nntp_hosts => [],
34
+ snpp_hosts => [],
35
+ pop3_hosts => [],
36
+ smtp_hosts => [],
37
+ ph_hosts => [],
38
+ daytime_hosts => [],
39
+ time_hosts => [],
40
+ inet_domain => undef,
41
+ ftp_firewall => undef,
42
+ ftp_ext_passive => 1,
43
+ ftp_int_passive => 1,
44
+ test_hosts => 1,
45
+ test_exist => 1,
46
+ );
47
+
48
+ #
49
+ # Try to get as much configuration info as possible from InternetConfig
50
+ #
51
+ {
52
+ ## no critic (BuiltinFunctions::ProhibitStringyEval)
53
+ $^O eq 'MacOS' and eval <<TRY_INTERNET_CONFIG;
54
+ use Mac::InternetConfig;
55
+
56
+ {
57
+ my %nc = (
58
+ nntp_hosts => [ \$InternetConfig{ kICNNTPHost() } ],
59
+ pop3_hosts => [ \$InternetConfig{ kICMailAccount() } =~ /\@(.*)/ ],
60
+ smtp_hosts => [ \$InternetConfig{ kICSMTPHost() } ],
61
+ ftp_testhost => \$InternetConfig{ kICFTPHost() } ? \$InternetConfig{ kICFTPHost()} : undef,
62
+ ph_hosts => [ \$InternetConfig{ kICPhHost() } ],
63
+ ftp_ext_passive => \$InternetConfig{"646F676F\xA5UsePassiveMode"} || 0,
64
+ ftp_int_passive => \$InternetConfig{"646F676F\xA5UsePassiveMode"} || 0,
65
+ socks_hosts =>
66
+ \$InternetConfig{ kICUseSocks() } ? [ \$InternetConfig{ kICSocksHost() } ] : [],
67
+ ftp_firewall =>
68
+ \$InternetConfig{ kICUseFTPProxy() } ? [ \$InternetConfig{ kICFTPProxyHost() } ] : [],
69
+ );
70
+ \@NetConfig{keys %nc} = values %nc;
71
+ }
72
+ TRY_INTERNET_CONFIG
73
+ }
74
+
75
+ my $file = __FILE__;
76
+ my $ref;
77
+ $file =~ s/Config.pm/libnet.cfg/;
78
+ if (-f $file) {
79
+ $ref = eval { local $SIG{__DIE__}; do $file };
80
+ if (ref($ref) eq 'HASH') {
81
+ %NetConfig = (%NetConfig, %{$ref});
82
+ $LIBNET_CFG = $file;
83
+ }
84
+ }
85
+ if ($< == $> and !$CONFIGURE) {
86
+ my $home = eval { local $SIG{__DIE__}; (getpwuid($>))[7] } || $ENV{HOME};
87
+ $home ||= $ENV{HOMEDRIVE} . ($ENV{HOMEPATH} || '') if defined $ENV{HOMEDRIVE};
88
+ if (defined $home) {
89
+ $file = $home . "/.libnetrc";
90
+ $ref = eval { local $SIG{__DIE__}; do $file } if -f $file;
91
+ %NetConfig = (%NetConfig, %{$ref})
92
+ if ref($ref) eq 'HASH';
93
+ }
94
+ }
95
+ my ($k, $v);
96
+ while (($k, $v) = each %NetConfig) {
97
+ $NetConfig{$k} = [$v]
98
+ if ($k =~ /_hosts$/ and $k ne "test_hosts" and defined($v) and !ref($v));
99
+ }
100
+
101
+ # Take a hostname and determine if it is inside the firewall
102
+
103
+
104
+ sub requires_firewall {
105
+ shift; # ignore package
106
+ my $host = shift;
107
+
108
+ return 0 unless defined $NetConfig{'ftp_firewall'};
109
+
110
+ $host = inet_aton($host) or return -1;
111
+ $host = inet_ntoa($host);
112
+
113
+ if (exists $NetConfig{'local_netmask'}) {
114
+ my $quad = unpack("N", pack("C*", split(/\./, $host)));
115
+ my $list = $NetConfig{'local_netmask'};
116
+ $list = [$list] unless ref($list);
117
+ foreach (@$list) {
118
+ my ($net, $bits) = (m#^(\d+\.\d+\.\d+\.\d+)/(\d+)$#) or next;
119
+ my $mask = ~0 << (32 - $bits);
120
+ my $addr = unpack("N", pack("C*", split(/\./, $net)));
121
+
122
+ return 0 if (($addr & $mask) == ($quad & $mask));
123
+ }
124
+ return 1;
125
+ }
126
+
127
+ return 0;
128
+ }
129
+
130
+ *is_external = \&requires_firewall;
131
+
132
+ 1;
133
+
134
+ __END__
135
+
136
+ =head1 NAME
137
+
138
+ Net::Config - Local configuration data for libnet
139
+
140
+ =head1 SYNOPSIS
141
+
142
+ use Net::Config qw(%NetConfig);
143
+
144
+ =head1 DESCRIPTION
145
+
146
+ C<Net::Config> holds configuration data for the modules in the libnet
147
+ distribution. During installation you will be asked for these values.
148
+
149
+ The configuration data is held globally in a file in the perl installation
150
+ tree, but a user may override any of these values by providing their own. This
151
+ can be done by having a C<.libnetrc> file in their home directory. This file
152
+ should return a reference to a HASH containing the keys described below.
153
+ For example
154
+
155
+ # .libnetrc
156
+ {
157
+ nntp_hosts => [ "my_preferred_host" ],
158
+ ph_hosts => [ "my_ph_server" ],
159
+ }
160
+ __END__
161
+
162
+ =head2 Class Methods
163
+
164
+ C<Net::Config> defines the following methods. They are methods as they are
165
+ invoked as class methods. This is because C<Net::Config> inherits from
166
+ C<Net::LocalCfg> so you can override these methods if you want.
167
+
168
+ =over 4
169
+
170
+ =item C<requires_firewall($host)>
171
+
172
+ Attempts to determine if a given host is outside your firewall. Possible
173
+ return values are.
174
+
175
+ -1 Cannot lookup hostname
176
+ 0 Host is inside firewall (or there is no ftp_firewall entry)
177
+ 1 Host is outside the firewall
178
+
179
+ This is done by using hostname lookup and the C<local_netmask> entry in
180
+ the configuration data.
181
+
182
+ =back
183
+
184
+ =head2 NetConfig Values
185
+
186
+ =over 4
187
+
188
+ =item nntp_hosts
189
+
190
+ =item snpp_hosts
191
+
192
+ =item pop3_hosts
193
+
194
+ =item smtp_hosts
195
+
196
+ =item ph_hosts
197
+
198
+ =item daytime_hosts
199
+
200
+ =item time_hosts
201
+
202
+ Each is a reference to an array of hostnames (in order of preference),
203
+ which should be used for the given protocol
204
+
205
+ =item inet_domain
206
+
207
+ Your internet domain name
208
+
209
+ =item ftp_firewall
210
+
211
+ If you have an FTP proxy firewall (B<NOT> an HTTP or SOCKS firewall)
212
+ then this value should be set to the firewall hostname. If your firewall
213
+ does not listen to port 21, then this value should be set to
214
+ C<"hostname:port"> (eg C<"hostname:99">)
215
+
216
+ =item ftp_firewall_type
217
+
218
+ There are many different ftp firewall products available. But unfortunately
219
+ there is no standard for how to traverse a firewall. The list below shows the
220
+ sequence of commands that Net::FTP will use
221
+
222
+ user Username for remote host
223
+ pass Password for remote host
224
+ fwuser Username for firewall
225
+ fwpass Password for firewall
226
+ remote.host The hostname of the remote ftp server
227
+
228
+ =over 4
229
+
230
+ =item 0Z<>
231
+
232
+ There is no firewall
233
+
234
+ =item 1Z<>
235
+
236
+ USER user@remote.host
237
+ PASS pass
238
+
239
+ =item 2Z<>
240
+
241
+ USER fwuser
242
+ PASS fwpass
243
+ USER user@remote.host
244
+ PASS pass
245
+
246
+ =item 3Z<>
247
+
248
+ USER fwuser
249
+ PASS fwpass
250
+ SITE remote.site
251
+ USER user
252
+ PASS pass
253
+
254
+ =item 4Z<>
255
+
256
+ USER fwuser
257
+ PASS fwpass
258
+ OPEN remote.site
259
+ USER user
260
+ PASS pass
261
+
262
+ =item 5Z<>
263
+
264
+ USER user@fwuser@remote.site
265
+ PASS pass@fwpass
266
+
267
+ =item 6Z<>
268
+
269
+ USER fwuser@remote.site
270
+ PASS fwpass
271
+ USER user
272
+ PASS pass
273
+
274
+ =item 7Z<>
275
+
276
+ USER user@remote.host
277
+ PASS pass
278
+ AUTH fwuser
279
+ RESP fwpass
280
+
281
+ =back
282
+
283
+ =item ftp_ext_passive
284
+
285
+ =item ftp_int_passive
286
+
287
+ FTP servers can work in passive or active mode. Active mode is when
288
+ you want to transfer data you have to tell the server the address and
289
+ port to connect to. Passive mode is when the server provide the
290
+ address and port and you establish the connection.
291
+
292
+ With some firewalls active mode does not work as the server cannot
293
+ connect to your machine (because you are behind a firewall) and the firewall
294
+ does not re-write the command. In this case you should set C<ftp_ext_passive>
295
+ to a I<true> value.
296
+
297
+ Some servers are configured to only work in passive mode. If you have
298
+ one of these you can force C<Net::FTP> to always transfer in passive
299
+ mode; when not going via a firewall, by setting C<ftp_int_passive> to
300
+ a I<true> value.
301
+
302
+ =item local_netmask
303
+
304
+ A reference to a list of netmask strings in the form C<"134.99.4.0/24">.
305
+ These are used by the C<requires_firewall> function to determine if a given
306
+ host is inside or outside your firewall.
307
+
308
+ =back
309
+
310
+ The following entries are used during installation & testing on the
311
+ libnet package
312
+
313
+ =over 4
314
+
315
+ =item test_hosts
316
+
317
+ If true then C<make test> may attempt to connect to hosts given in the
318
+ configuration.
319
+
320
+ =item test_exists
321
+
322
+ If true then C<Configure> will check each hostname given that it exists
323
+
324
+ =back
325
+
326
+ =head1 EXPORTS
327
+
328
+ The following symbols are, or can be, exported by this module:
329
+
330
+ =over 4
331
+
332
+ =item Default Exports
333
+
334
+ C<%NetConfig>.
335
+
336
+ =item Optional Exports
337
+
338
+ I<None>.
339
+
340
+ =item Export Tags
341
+
342
+ I<None>.
343
+
344
+ =back
345
+
346
+ =head1 KNOWN BUGS
347
+
348
+ I<None>.
349
+
350
+ =head1 AUTHOR
351
+
352
+ Graham Barr E<lt>L<gbarr@pobox.com|mailto:gbarr@pobox.com>E<gt>.
353
+
354
+ Steve Hay E<lt>L<shay@cpan.org|mailto:shay@cpan.org>E<gt> is now maintaining
355
+ libnet as of version 1.22_02.
356
+
357
+ =head1 COPYRIGHT
358
+
359
+ Copyright (C) 2000 Graham Barr. All rights reserved.
360
+
361
+ Copyright (C) 2013-2014, 2016, 2020 Steve Hay. All rights reserved.
362
+
363
+ =head1 LICENCE
364
+
365
+ This module is free software; you can redistribute it and/or modify it under the
366
+ same terms as Perl itself, i.e. under the terms of either the GNU General Public
367
+ License or the Artistic License, as specified in the F<LICENCE> file.
368
+
369
+ =head1 VERSION
370
+
371
+ Version 3.15
372
+
373
+ =head1 DATE
374
+
375
+ 20 March 2023
376
+
377
+ =head1 HISTORY
378
+
379
+ See the F<Changes> file.
380
+
381
+ =cut
git/usr/share/perl5/core_perl/Net/Domain.pm ADDED
@@ -0,0 +1,408 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Net::Domain.pm
2
+ #
3
+ # Copyright (C) 1995-1998 Graham Barr. All rights reserved.
4
+ # Copyright (C) 2013-2014, 2020 Steve Hay. All rights reserved.
5
+ # This module is free software; you can redistribute it and/or modify it under
6
+ # the same terms as Perl itself, i.e. under the terms of either the GNU General
7
+ # Public License or the Artistic License, as specified in the F<LICENCE> file.
8
+
9
+ package Net::Domain;
10
+
11
+ use 5.008001;
12
+
13
+ use strict;
14
+ use warnings;
15
+
16
+ use Carp;
17
+ use Exporter;
18
+ use Net::Config;
19
+
20
+ our @ISA = qw(Exporter);
21
+ our @EXPORT_OK = qw(hostname hostdomain hostfqdn domainname);
22
+ our $VERSION = "3.15";
23
+
24
+ my ($host, $domain, $fqdn) = (undef, undef, undef);
25
+
26
+ # Try every conceivable way to get hostname.
27
+
28
+
29
+ sub _hostname {
30
+
31
+ # we already know it
32
+ return $host
33
+ if (defined $host);
34
+
35
+ if ($^O eq 'MSWin32') {
36
+ require Socket;
37
+ my ($name, $alias, $type, $len, @addr) = gethostbyname($ENV{'COMPUTERNAME'} || 'localhost');
38
+ while (@addr) {
39
+ my $a = shift(@addr);
40
+ $host = gethostbyaddr($a, Socket::AF_INET());
41
+ last if defined $host;
42
+ }
43
+ if (defined($host) && index($host, '.') > 0) {
44
+ $fqdn = $host;
45
+ ($host, $domain) = $fqdn =~ /^([^.]+)\.(.*)$/;
46
+ }
47
+ return $host;
48
+ }
49
+ elsif ($^O eq 'MacOS') {
50
+ chomp($host = `hostname`);
51
+ }
52
+ elsif ($^O eq 'VMS') { ## multiple varieties of net s/w makes this hard
53
+ $host = $ENV{'UCX$INET_HOST'} if defined($ENV{'UCX$INET_HOST'});
54
+ $host = $ENV{'MULTINET_HOST_NAME'} if defined($ENV{'MULTINET_HOST_NAME'});
55
+ if (index($host, '.') > 0) {
56
+ $fqdn = $host;
57
+ ($host, $domain) = $fqdn =~ /^([^.]+)\.(.*)$/;
58
+ }
59
+ return $host;
60
+ }
61
+ else {
62
+ local $SIG{'__DIE__'};
63
+
64
+ # syscall is preferred since it avoids tainting problems
65
+ eval {
66
+ my $tmp = "\0" x 256; ## preload scalar
67
+ eval {
68
+ package main;
69
+ require "syscall.ph"; ## no critic (Modules::RequireBarewordIncludes)
70
+ defined(&main::SYS_gethostname);
71
+ }
72
+ || eval {
73
+ package main;
74
+ require "sys/syscall.ph"; ## no critic (Modules::RequireBarewordIncludes)
75
+ defined(&main::SYS_gethostname);
76
+ }
77
+ and $host =
78
+ (syscall(&main::SYS_gethostname, $tmp, 256) == 0)
79
+ ? $tmp
80
+ : undef;
81
+ }
82
+
83
+ # POSIX
84
+ || eval {
85
+ require POSIX;
86
+ $host = (POSIX::uname())[1];
87
+ }
88
+
89
+ # trusty old hostname command
90
+ || eval {
91
+ chop($host = `(hostname) 2>/dev/null`); # BSD'ish
92
+ }
93
+
94
+ # sysV/POSIX uname command (may truncate)
95
+ || eval {
96
+ chop($host = `uname -n 2>/dev/null`); ## SYSV'ish && POSIX'ish
97
+ }
98
+
99
+ # Apollo pre-SR10
100
+ || eval { $host = (split(/[:. ]/, `/com/host`, 6))[0]; }
101
+
102
+ || eval { $host = ""; };
103
+ }
104
+
105
+ # remove garbage
106
+ $host =~ s/[\0\r\n]+//go;
107
+ $host =~ s/(\A\.+|\.+\Z)//go;
108
+ $host =~ s/\.\.+/\./go;
109
+
110
+ $host;
111
+ }
112
+
113
+
114
+ sub _hostdomain {
115
+
116
+ # we already know it
117
+ return $domain
118
+ if (defined $domain);
119
+
120
+ local $SIG{'__DIE__'};
121
+
122
+ return $domain = $NetConfig{'inet_domain'}
123
+ if defined $NetConfig{'inet_domain'};
124
+
125
+ # try looking in /etc/resolv.conf
126
+ # putting this here and assuming that it is correct, eliminates
127
+ # calls to gethostbyname, and therefore DNS lookups. This helps
128
+ # those on dialup systems.
129
+
130
+ local ($_);
131
+
132
+ if (open(my $res, '<', "/etc/resolv.conf")) {
133
+ while (<$res>) {
134
+ $domain = $1
135
+ if (/\A\s*(?:domain|search)\s+(\S+)/);
136
+ }
137
+ close($res);
138
+
139
+ return $domain
140
+ if (defined $domain);
141
+ }
142
+
143
+ # just try hostname and system calls
144
+
145
+ my $host = _hostname();
146
+ my (@hosts);
147
+
148
+ @hosts = ($host, "localhost");
149
+
150
+ unless (defined($host) && $host =~ /\./) {
151
+ my $dom = undef;
152
+ eval {
153
+ my $tmp = "\0" x 256; ## preload scalar
154
+ eval {
155
+ package main;
156
+ require "syscall.ph"; ## no critic (Modules::RequireBarewordIncludes)
157
+ }
158
+ || eval {
159
+ package main;
160
+ require "sys/syscall.ph"; ## no critic (Modules::RequireBarewordIncludes)
161
+ }
162
+ and $dom =
163
+ (syscall(&main::SYS_getdomainname, $tmp, 256) == 0)
164
+ ? $tmp
165
+ : undef;
166
+ };
167
+
168
+ if ($^O eq 'VMS') {
169
+ $dom ||= $ENV{'TCPIP$INET_DOMAIN'}
170
+ || $ENV{'UCX$INET_DOMAIN'};
171
+ }
172
+
173
+ chop($dom = `domainname 2>/dev/null`)
174
+ unless (defined $dom || $^O =~ /^(?:cygwin|MSWin32|android)/);
175
+
176
+ if (defined $dom) {
177
+ my @h = ();
178
+ $dom =~ s/^\.+//;
179
+ while (length($dom)) {
180
+ push(@h, "$host.$dom");
181
+ $dom =~ s/^[^.]+.+// or last;
182
+ }
183
+ unshift(@hosts, @h);
184
+ }
185
+ }
186
+
187
+ # Attempt to locate FQDN
188
+
189
+ foreach (grep { defined $_ } @hosts) {
190
+ my @info = gethostbyname($_);
191
+
192
+ next unless @info;
193
+
194
+ # look at real name & aliases
195
+ foreach my $site ($info[0], split(/ /, $info[1])) {
196
+ if (rindex($site, ".") > 0) {
197
+
198
+ # Extract domain from FQDN
199
+
200
+ ($domain = $site) =~ s/\A[^.]+\.//;
201
+ return $domain;
202
+ }
203
+ }
204
+ }
205
+
206
+ # Look for environment variable
207
+
208
+ $domain ||= $ENV{LOCALDOMAIN} || $ENV{DOMAIN};
209
+
210
+ if (defined $domain) {
211
+ $domain =~ s/[\r\n\0]+//g;
212
+ $domain =~ s/(\A\.+|\.+\Z)//g;
213
+ $domain =~ s/\.\.+/\./g;
214
+ }
215
+
216
+ $domain;
217
+ }
218
+
219
+
220
+ sub domainname {
221
+
222
+ return $fqdn
223
+ if (defined $fqdn);
224
+
225
+ _hostname();
226
+
227
+ # *.local names are special on darwin. If we call gethostbyname below, it
228
+ # may hang while waiting for another, non-existent computer to respond.
229
+ if($^O eq 'darwin' && $host =~ /\.local$/) {
230
+ return $host;
231
+ }
232
+
233
+ _hostdomain();
234
+
235
+ # Assumption: If the host name does not contain a period
236
+ # and the domain name does, then assume that they are correct
237
+ # this helps to eliminate calls to gethostbyname, and therefore
238
+ # eliminate DNS lookups
239
+
240
+ return $fqdn = $host . "." . $domain
241
+ if (defined $host
242
+ and defined $domain
243
+ and $host !~ /\./
244
+ and $domain =~ /\./);
245
+
246
+ # For hosts that have no name, just an IP address
247
+ return $fqdn = $host if defined $host and $host =~ /^\d+(\.\d+){3}$/;
248
+
249
+ my @host = defined $host ? split(/\./, $host) : ('localhost');
250
+ my @domain = defined $domain ? split(/\./, $domain) : ();
251
+ my @fqdn = ();
252
+
253
+ # Determine from @host & @domain the FQDN
254
+
255
+ my @d = @domain;
256
+
257
+ LOOP:
258
+ while (1) {
259
+ my @h = @host;
260
+ while (@h) {
261
+ my $tmp = join(".", @h, @d);
262
+ if ((gethostbyname($tmp))[0]) {
263
+ @fqdn = (@h, @d);
264
+ $fqdn = $tmp;
265
+ last LOOP;
266
+ }
267
+ pop @h;
268
+ }
269
+ last unless shift @d;
270
+ }
271
+
272
+ if (@fqdn) {
273
+ $host = shift @fqdn;
274
+ until ((gethostbyname($host))[0]) {
275
+ $host .= "." . shift @fqdn;
276
+ }
277
+ $domain = join(".", @fqdn);
278
+ }
279
+ else {
280
+ undef $host;
281
+ undef $domain;
282
+ undef $fqdn;
283
+ }
284
+
285
+ $fqdn;
286
+ }
287
+
288
+
289
+ sub hostfqdn { domainname() }
290
+
291
+
292
+ sub hostname {
293
+ domainname()
294
+ unless (defined $host);
295
+ return $host;
296
+ }
297
+
298
+
299
+ sub hostdomain {
300
+ domainname()
301
+ unless (defined $domain);
302
+ return $domain;
303
+ }
304
+
305
+ 1; # Keep require happy
306
+
307
+ __END__
308
+
309
+ =head1 NAME
310
+
311
+ Net::Domain - Attempt to evaluate the current host's internet name and domain
312
+
313
+ =head1 SYNOPSIS
314
+
315
+ use Net::Domain qw(hostname hostfqdn hostdomain domainname);
316
+
317
+ =head1 DESCRIPTION
318
+
319
+ Using various methods B<attempt> to find the Fully Qualified Domain Name (FQDN)
320
+ of the current host. From this determine the host-name and the host-domain.
321
+
322
+ Each of the functions will return I<undef> if the FQDN cannot be determined.
323
+
324
+ =head2 Functions
325
+
326
+ =over 4
327
+
328
+ =item C<hostfqdn()>
329
+
330
+ Identify and return the FQDN of the current host.
331
+
332
+ =item C<domainname()>
333
+
334
+ An alias for hostfqdn().
335
+
336
+ =item C<hostname()>
337
+
338
+ Returns the smallest part of the FQDN which can be used to identify the host.
339
+
340
+ =item C<hostdomain()>
341
+
342
+ Returns the remainder of the FQDN after the I<hostname> has been removed.
343
+
344
+ =back
345
+
346
+ =head1 EXPORTS
347
+
348
+ The following symbols are, or can be, exported by this module:
349
+
350
+ =over 4
351
+
352
+ =item Default Exports
353
+
354
+ I<None>.
355
+
356
+ =item Optional Exports
357
+
358
+ C<hostname>,
359
+ C<hostdomain>,
360
+ C<hostfqdn>,
361
+ C<domainname>.
362
+
363
+ =item Export Tags
364
+
365
+ I<None>.
366
+
367
+ =back
368
+
369
+
370
+ =head1 KNOWN BUGS
371
+
372
+ See L<https://rt.cpan.org/Dist/Display.html?Status=Active&Queue=libnet>.
373
+
374
+ =head1 AUTHOR
375
+
376
+ Graham Barr E<lt>L<gbarr@pobox.com|mailto:gbarr@pobox.com>E<gt>.
377
+
378
+ Adapted from Sys::Hostname by David Sundstrom
379
+ E<lt>L<sunds@asictest.sc.ti.com|mailto:sunds@asictest.sc.ti.com>E<gt>.
380
+
381
+ Steve Hay E<lt>L<shay@cpan.org|mailto:shay@cpan.org>E<gt> is now maintaining
382
+ libnet as of version 1.22_02.
383
+
384
+ =head1 COPYRIGHT
385
+
386
+ Copyright (C) 1995-1998 Graham Barr. All rights reserved.
387
+
388
+ Copyright (C) 2013-2014, 2020 Steve Hay. All rights reserved.
389
+
390
+ =head1 LICENCE
391
+
392
+ This module is free software; you can redistribute it and/or modify it under the
393
+ same terms as Perl itself, i.e. under the terms of either the GNU General Public
394
+ License or the Artistic License, as specified in the F<LICENCE> file.
395
+
396
+ =head1 VERSION
397
+
398
+ Version 3.15
399
+
400
+ =head1 DATE
401
+
402
+ 20 March 2023
403
+
404
+ =head1 HISTORY
405
+
406
+ See the F<Changes> file.
407
+
408
+ =cut
git/usr/share/perl5/core_perl/Net/FTP.pm ADDED
@@ -0,0 +1,2037 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Net::FTP.pm
2
+ #
3
+ # Copyright (C) 1995-2004 Graham Barr. All rights reserved.
4
+ # Copyright (C) 2013-2017, 2020, 2022 Steve Hay. All rights reserved.
5
+ # This module is free software; you can redistribute it and/or modify it under
6
+ # the same terms as Perl itself, i.e. under the terms of either the GNU General
7
+ # Public License or the Artistic License, as specified in the F<LICENCE> file.
8
+ #
9
+ # Documentation (at end) improved 1996 by Nathan Torkington <gnat@frii.com>.
10
+
11
+ package Net::FTP;
12
+
13
+ use 5.008001;
14
+
15
+ use strict;
16
+ use warnings;
17
+
18
+ use Carp;
19
+ use Fcntl qw(O_WRONLY O_RDONLY O_APPEND O_CREAT O_TRUNC);
20
+ use IO::Socket;
21
+ use Net::Cmd;
22
+ use Net::Config;
23
+ use Socket;
24
+ use Time::Local;
25
+
26
+ our $VERSION = '3.15';
27
+
28
+ our $IOCLASS;
29
+ my $family_key;
30
+ BEGIN {
31
+ # Code for detecting if we can use SSL
32
+ my $ssl_class = eval {
33
+ require IO::Socket::SSL;
34
+ # first version with default CA on most platforms
35
+ no warnings 'numeric';
36
+ IO::Socket::SSL->VERSION(2.007);
37
+ } && 'IO::Socket::SSL';
38
+
39
+ my $nossl_warn = !$ssl_class &&
40
+ 'To use SSL please install IO::Socket::SSL with version>=2.007';
41
+
42
+ # Code for detecting if we can use IPv6
43
+ my $inet6_class = eval {
44
+ require IO::Socket::IP;
45
+ no warnings 'numeric';
46
+ IO::Socket::IP->VERSION(0.25);
47
+ } && 'IO::Socket::IP' || eval {
48
+ require IO::Socket::INET6;
49
+ no warnings 'numeric';
50
+ IO::Socket::INET6->VERSION(2.62);
51
+ } && 'IO::Socket::INET6';
52
+
53
+ sub can_ssl { $ssl_class };
54
+ sub can_inet6 { $inet6_class };
55
+
56
+ $IOCLASS = $ssl_class || $inet6_class || 'IO::Socket::INET';
57
+ $family_key =
58
+ ( $ssl_class ? $ssl_class->can_ipv6 : $inet6_class || '' )
59
+ eq 'IO::Socket::IP'
60
+ ? 'Family' : 'Domain';
61
+ }
62
+
63
+ our @ISA = ('Exporter','Net::Cmd',$IOCLASS);
64
+
65
+ use constant TELNET_IAC => 255;
66
+ use constant TELNET_IP => 244;
67
+ use constant TELNET_DM => 242;
68
+
69
+ use constant EBCDIC => ord 'A' == 193;
70
+
71
+ sub new {
72
+ my $pkg = shift;
73
+ my ($peer, %arg);
74
+ if (@_ % 2) {
75
+ $peer = shift;
76
+ %arg = @_;
77
+ }
78
+ else {
79
+ %arg = @_;
80
+ $peer = delete $arg{Host};
81
+ }
82
+
83
+ my $host = $peer;
84
+ my $fire = undef;
85
+ my $fire_type = undef;
86
+
87
+ if (exists($arg{Firewall}) || Net::Config->requires_firewall($peer)) {
88
+ $fire = $arg{Firewall}
89
+ || $ENV{FTP_FIREWALL}
90
+ || $NetConfig{ftp_firewall}
91
+ || undef;
92
+
93
+ if (defined $fire) {
94
+ $peer = $fire;
95
+ delete $arg{Port};
96
+ $fire_type = $arg{FirewallType}
97
+ || $ENV{FTP_FIREWALL_TYPE}
98
+ || $NetConfig{firewall_type}
99
+ || undef;
100
+ }
101
+ }
102
+
103
+ my %tlsargs;
104
+ if (can_ssl()) {
105
+ # for name verification strip port from domain:port, ipv4:port, [ipv6]:port
106
+ (my $hostname = $host) =~s{(?<!:):\d+$}{};
107
+ %tlsargs = (
108
+ SSL_verifycn_scheme => 'ftp',
109
+ SSL_verifycn_name => $hostname,
110
+ # use SNI if supported by IO::Socket::SSL
111
+ $pkg->can_client_sni ? (SSL_hostname => $hostname):(),
112
+ # reuse SSL session of control connection in data connections
113
+ SSL_session_cache_size => 10,
114
+ SSL_session_key => $hostname,
115
+ );
116
+ # user defined SSL arg
117
+ $tlsargs{$_} = $arg{$_} for(grep { m{^SSL_} } keys %arg);
118
+ $tlsargs{SSL_reuse_ctx} = IO::Socket::SSL::SSL_Context->new(%tlsargs)
119
+ or return;
120
+
121
+ } elsif ($arg{SSL}) {
122
+ croak("IO::Socket::SSL >= 2.007 needed for SSL support");
123
+ }
124
+
125
+ my $ftp = $pkg->SUPER::new(
126
+ PeerAddr => $peer,
127
+ PeerPort => $arg{Port} || ($arg{SSL} ? 'ftps(990)' : 'ftp(21)'),
128
+ LocalAddr => $arg{'LocalAddr'},
129
+ $family_key => $arg{Domain} || $arg{Family},
130
+ Proto => 'tcp',
131
+ Timeout => defined $arg{Timeout} ? $arg{Timeout} : 120,
132
+ %tlsargs,
133
+ $arg{SSL} ? ():( SSL_startHandshake => 0 ),
134
+ ) or return;
135
+
136
+ ${*$ftp}{'net_ftp_host'} = $host; # Remote hostname
137
+ ${*$ftp}{'net_ftp_type'} = 'A'; # ASCII/binary/etc mode
138
+ ${*$ftp}{'net_ftp_blksize'} = abs($arg{'BlockSize'} || 10240);
139
+
140
+ ${*$ftp}{'net_ftp_localaddr'} = $arg{'LocalAddr'};
141
+ ${*$ftp}{'net_ftp_domain'} = $arg{Domain} || $arg{Family};
142
+
143
+ ${*$ftp}{'net_ftp_firewall'} = $fire
144
+ if (defined $fire);
145
+ ${*$ftp}{'net_ftp_firewall_type'} = $fire_type
146
+ if (defined $fire_type);
147
+
148
+ ${*$ftp}{'net_ftp_passive'} =
149
+ int exists $arg{Passive} ? $arg{Passive}
150
+ : exists $ENV{FTP_PASSIVE} ? $ENV{FTP_PASSIVE}
151
+ : defined $fire ? $NetConfig{ftp_ext_passive}
152
+ : $NetConfig{ftp_int_passive}; # Whew! :-)
153
+
154
+ ${*$ftp}{net_ftp_tlsargs} = \%tlsargs if %tlsargs;
155
+ if ($arg{SSL}) {
156
+ ${*$ftp}{net_ftp_tlsprot} = 'P';
157
+ ${*$ftp}{net_ftp_tlsdirect} = 1;
158
+ }
159
+
160
+ $ftp->hash(exists $arg{Hash} ? $arg{Hash} : 0, 1024);
161
+
162
+ $ftp->autoflush(1);
163
+
164
+ $ftp->debug(exists $arg{Debug} ? $arg{Debug} : undef);
165
+
166
+ unless ($ftp->response() == CMD_OK) {
167
+ $ftp->close();
168
+ # keep @$ if no message. Happens, when response did not start with a code.
169
+ $@ = $ftp->message || $@;
170
+ undef $ftp;
171
+ }
172
+
173
+ $ftp;
174
+ }
175
+
176
+ ##
177
+ ## User interface methods
178
+ ##
179
+
180
+
181
+ sub host {
182
+ my $me = shift;
183
+ ${*$me}{'net_ftp_host'};
184
+ }
185
+
186
+ sub passive {
187
+ my $ftp = shift;
188
+ return ${*$ftp}{'net_ftp_passive'} unless @_;
189
+ ${*$ftp}{'net_ftp_passive'} = shift;
190
+ }
191
+
192
+
193
+ sub hash {
194
+ my $ftp = shift; # self
195
+
196
+ my ($h, $b) = @_;
197
+ unless ($h) {
198
+ delete ${*$ftp}{'net_ftp_hash'};
199
+ return [\*STDERR, 0];
200
+ }
201
+ ($h, $b) = (ref($h) ? $h : \*STDERR, $b || 1024);
202
+ select((select($h), $| = 1)[0]);
203
+ $b = 512 if $b < 512;
204
+ ${*$ftp}{'net_ftp_hash'} = [$h, $b];
205
+ }
206
+
207
+
208
+ sub quit {
209
+ my $ftp = shift;
210
+
211
+ $ftp->_QUIT;
212
+ $ftp->close;
213
+ }
214
+
215
+
216
+ sub DESTROY { }
217
+
218
+
219
+ sub ascii { shift->type('A', @_); }
220
+ sub binary { shift->type('I', @_); }
221
+
222
+
223
+ sub ebcdic {
224
+ carp "TYPE E is unsupported, shall default to I";
225
+ shift->type('E', @_);
226
+ }
227
+
228
+
229
+ sub byte {
230
+ carp "TYPE L is unsupported, shall default to I";
231
+ shift->type('L', @_);
232
+ }
233
+
234
+ # Allow the user to send a command directly, BE CAREFUL !!
235
+
236
+
237
+ sub quot {
238
+ my $ftp = shift;
239
+ my $cmd = shift;
240
+
241
+ $ftp->command(uc $cmd, @_);
242
+ $ftp->response();
243
+ }
244
+
245
+
246
+ sub site {
247
+ my $ftp = shift;
248
+
249
+ $ftp->command("SITE", @_);
250
+ $ftp->response();
251
+ }
252
+
253
+
254
+ sub mdtm {
255
+ my $ftp = shift;
256
+ my $file = shift;
257
+
258
+ # Server Y2K bug workaround
259
+ #
260
+ # sigh; some idiotic FTP servers use ("19%d",tm.tm_year) instead of
261
+ # ("%d",tm.tm_year+1900). This results in an extra digit in the
262
+ # string returned. To account for this we allow an optional extra
263
+ # digit in the year. Then if the first two digits are 19 we use the
264
+ # remainder, otherwise we subtract 1900 from the whole year.
265
+
266
+ $ftp->_MDTM($file)
267
+ && $ftp->message =~ /((\d\d)(\d\d\d?))(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)/
268
+ ? timegm($8, $7, $6, $5, $4 - 1, $2 eq '19' ? ($3 + 1900) : $1)
269
+ : undef;
270
+ }
271
+
272
+
273
+ sub size {
274
+ my $ftp = shift;
275
+ my $file = shift;
276
+ my $io;
277
+ if ($ftp->supported("SIZE")) {
278
+ return $ftp->_SIZE($file)
279
+ ? ($ftp->message =~ /(\d+)\s*(bytes?\s*)?$/)[0]
280
+ : undef;
281
+ }
282
+ elsif ($ftp->supported("STAT")) {
283
+ my @msg;
284
+ return
285
+ unless $ftp->_STAT($file) && (@msg = $ftp->message) == 3;
286
+ foreach my $line (@msg) {
287
+ return (split(/\s+/, $line))[4]
288
+ if $line =~ /^[-rwxSsTt]{10}/;
289
+ }
290
+ }
291
+ else {
292
+ my @files = $ftp->dir($file);
293
+ if (@files) {
294
+ return (split(/\s+/, $1))[4]
295
+ if $files[0] =~ /^([-rwxSsTt]{10}.*)$/;
296
+ }
297
+ }
298
+ undef;
299
+ }
300
+
301
+
302
+ sub starttls {
303
+ my $ftp = shift;
304
+ can_ssl() or croak("IO::Socket::SSL >= 2.007 needed for SSL support");
305
+ $ftp->is_SSL and croak("called starttls within SSL session");
306
+ $ftp->_AUTH('TLS') == CMD_OK or return;
307
+
308
+ $ftp->connect_SSL or return;
309
+ $ftp->prot('P');
310
+ return 1;
311
+ }
312
+
313
+ sub prot {
314
+ my ($ftp,$prot) = @_;
315
+ $prot eq 'C' or $prot eq 'P' or croak("prot must by C or P");
316
+ $ftp->_PBSZ(0) or return;
317
+ $ftp->_PROT($prot) or return;
318
+ ${*$ftp}{net_ftp_tlsprot} = $prot;
319
+ return 1;
320
+ }
321
+
322
+ sub stoptls {
323
+ my $ftp = shift;
324
+ $ftp->is_SSL or croak("called stoptls outside SSL session");
325
+ ${*$ftp}{net_ftp_tlsdirect} and croak("cannot stoptls direct SSL session");
326
+ $ftp->_CCC() or return;
327
+ $ftp->stop_SSL();
328
+ return 1;
329
+ }
330
+
331
+ sub login {
332
+ my ($ftp, $user, $pass, $acct) = @_;
333
+ my ($ok, $ruser, $fwtype);
334
+
335
+ unless (defined $user) {
336
+ require Net::Netrc;
337
+
338
+ my $rc = Net::Netrc->lookup(${*$ftp}{'net_ftp_host'});
339
+
340
+ ($user, $pass, $acct) = $rc->lpa()
341
+ if ($rc);
342
+ }
343
+
344
+ $user ||= "anonymous";
345
+ $ruser = $user;
346
+
347
+ $fwtype = ${*$ftp}{'net_ftp_firewall_type'}
348
+ || $NetConfig{'ftp_firewall_type'}
349
+ || 0;
350
+
351
+ if ($fwtype && defined ${*$ftp}{'net_ftp_firewall'}) {
352
+ if ($fwtype == 1 || $fwtype == 7) {
353
+ $user .= '@' . ${*$ftp}{'net_ftp_host'};
354
+ }
355
+ else {
356
+ require Net::Netrc;
357
+
358
+ my $rc = Net::Netrc->lookup(${*$ftp}{'net_ftp_firewall'});
359
+
360
+ my ($fwuser, $fwpass, $fwacct) = $rc ? $rc->lpa() : ();
361
+
362
+ if ($fwtype == 5) {
363
+ $user = join('@', $user, $fwuser, ${*$ftp}{'net_ftp_host'});
364
+ $pass = $pass . '@' . $fwpass;
365
+ }
366
+ else {
367
+ if ($fwtype == 2) {
368
+ $user .= '@' . ${*$ftp}{'net_ftp_host'};
369
+ }
370
+ elsif ($fwtype == 6) {
371
+ $fwuser .= '@' . ${*$ftp}{'net_ftp_host'};
372
+ }
373
+
374
+ $ok = $ftp->_USER($fwuser);
375
+
376
+ return 0 unless $ok == CMD_OK || $ok == CMD_MORE;
377
+
378
+ $ok = $ftp->_PASS($fwpass || "");
379
+
380
+ return 0 unless $ok == CMD_OK || $ok == CMD_MORE;
381
+
382
+ $ok = $ftp->_ACCT($fwacct)
383
+ if defined($fwacct);
384
+
385
+ if ($fwtype == 3) {
386
+ $ok = $ftp->command("SITE", ${*$ftp}{'net_ftp_host'})->response;
387
+ }
388
+ elsif ($fwtype == 4) {
389
+ $ok = $ftp->command("OPEN", ${*$ftp}{'net_ftp_host'})->response;
390
+ }
391
+
392
+ return 0 unless $ok == CMD_OK || $ok == CMD_MORE;
393
+ }
394
+ }
395
+ }
396
+
397
+ $ok = $ftp->_USER($user);
398
+
399
+ # Some dumb firewalls don't prefix the connection messages
400
+ $ok = $ftp->response()
401
+ if ($ok == CMD_OK && $ftp->code == 220 && $user =~ /\@/);
402
+
403
+ if ($ok == CMD_MORE) {
404
+ unless (defined $pass) {
405
+ require Net::Netrc;
406
+
407
+ my $rc = Net::Netrc->lookup(${*$ftp}{'net_ftp_host'}, $ruser);
408
+
409
+ ($ruser, $pass, $acct) = $rc->lpa()
410
+ if ($rc);
411
+
412
+ $pass = '-anonymous@'
413
+ if (!defined $pass && (!defined($ruser) || $ruser =~ /^anonymous/o));
414
+ }
415
+
416
+ $ok = $ftp->_PASS($pass || "");
417
+ }
418
+
419
+ $ok = $ftp->_ACCT($acct)
420
+ if (defined($acct) && ($ok == CMD_MORE || $ok == CMD_OK));
421
+
422
+ if ($fwtype == 7 && $ok == CMD_OK && defined ${*$ftp}{'net_ftp_firewall'}) {
423
+ my ($f, $auth, $resp) = _auth_id($ftp);
424
+ $ftp->authorize($auth, $resp) if defined($resp);
425
+ }
426
+
427
+ $ok == CMD_OK;
428
+ }
429
+
430
+
431
+ sub account {
432
+ @_ == 2 or croak 'usage: $ftp->account($acct)';
433
+ my $ftp = shift;
434
+ my $acct = shift;
435
+ $ftp->_ACCT($acct) == CMD_OK;
436
+ }
437
+
438
+
439
+ sub _auth_id {
440
+ my ($ftp, $auth, $resp) = @_;
441
+
442
+ unless (defined $resp) {
443
+ require Net::Netrc;
444
+
445
+ $auth ||= eval { (getpwuid($>))[0] } || $ENV{NAME};
446
+
447
+ my $rc = Net::Netrc->lookup(${*$ftp}{'net_ftp_firewall'}, $auth)
448
+ || Net::Netrc->lookup(${*$ftp}{'net_ftp_firewall'});
449
+
450
+ ($auth, $resp) = $rc->lpa()
451
+ if ($rc);
452
+ }
453
+ ($ftp, $auth, $resp);
454
+ }
455
+
456
+
457
+ sub authorize {
458
+ @_ >= 1 || @_ <= 3 or croak 'usage: $ftp->authorize([$auth[, $resp]])';
459
+
460
+ my ($ftp, $auth, $resp) = &_auth_id;
461
+
462
+ my $ok = $ftp->_AUTH($auth || "");
463
+
464
+ return $ftp->_RESP($resp || "")
465
+ if ($ok == CMD_MORE);
466
+
467
+ $ok == CMD_OK;
468
+ }
469
+
470
+
471
+ sub rename {
472
+ @_ == 3 or croak 'usage: $ftp->rename($oldname, $newname)';
473
+
474
+ my ($ftp, $oldname, $newname) = @_;
475
+
476
+ $ftp->_RNFR($oldname)
477
+ && $ftp->_RNTO($newname);
478
+ }
479
+
480
+
481
+ sub type {
482
+ my $ftp = shift;
483
+ my $type = shift;
484
+ my $oldval = ${*$ftp}{'net_ftp_type'};
485
+
486
+ return $oldval
487
+ unless (defined $type);
488
+
489
+ return
490
+ unless ($ftp->_TYPE($type, @_));
491
+
492
+ ${*$ftp}{'net_ftp_type'} = join(" ", $type, @_);
493
+
494
+ $oldval;
495
+ }
496
+
497
+
498
+ sub alloc {
499
+ my $ftp = shift;
500
+ my $size = shift;
501
+ my $oldval = ${*$ftp}{'net_ftp_allo'};
502
+
503
+ return $oldval
504
+ unless (defined $size);
505
+
506
+ return
507
+ unless ($ftp->supported("ALLO") and $ftp->_ALLO($size, @_));
508
+
509
+ ${*$ftp}{'net_ftp_allo'} = join(" ", $size, @_);
510
+
511
+ $oldval;
512
+ }
513
+
514
+
515
+ sub abort {
516
+ my $ftp = shift;
517
+
518
+ send($ftp, pack("CCC", TELNET_IAC, TELNET_IP, TELNET_IAC), MSG_OOB);
519
+
520
+ $ftp->command(pack("C", TELNET_DM) . "ABOR");
521
+
522
+ ${*$ftp}{'net_ftp_dataconn'}->close()
523
+ if defined ${*$ftp}{'net_ftp_dataconn'};
524
+
525
+ $ftp->response();
526
+
527
+ $ftp->status == CMD_OK;
528
+ }
529
+
530
+
531
+ sub get {
532
+ my ($ftp, $remote, $local, $where) = @_;
533
+
534
+ my ($loc, $len, $buf, $resp, $data);
535
+ local *FD;
536
+
537
+ my $localfd = ref($local) || ref(\$local) eq "GLOB";
538
+
539
+ ($local = $remote) =~ s#^.*/##
540
+ unless (defined $local);
541
+
542
+ croak("Bad remote filename '$remote'\n")
543
+ if $remote =~ /[\r\n]/s;
544
+
545
+ ${*$ftp}{'net_ftp_rest'} = $where if defined $where;
546
+ my $rest = ${*$ftp}{'net_ftp_rest'};
547
+
548
+ delete ${*$ftp}{'net_ftp_port'};
549
+ delete ${*$ftp}{'net_ftp_pasv'};
550
+
551
+ $data = $ftp->retr($remote)
552
+ or return;
553
+
554
+ if ($localfd) {
555
+ $loc = $local;
556
+ }
557
+ else {
558
+ $loc = \*FD;
559
+
560
+ unless (sysopen($loc, $local, O_CREAT | O_WRONLY | ($rest ? O_APPEND: O_TRUNC))) {
561
+ carp "Cannot open Local file $local: $!\n";
562
+ $data->abort;
563
+ return;
564
+ }
565
+ }
566
+
567
+ if ($ftp->type eq 'I' && !binmode($loc)) {
568
+ carp "Cannot binmode Local file $local: $!\n";
569
+ $data->abort;
570
+ close($loc) unless $localfd;
571
+ return;
572
+ }
573
+
574
+ $buf = '';
575
+ my ($count, $hashh, $hashb, $ref) = (0);
576
+
577
+ ($hashh, $hashb) = @$ref
578
+ if ($ref = ${*$ftp}{'net_ftp_hash'});
579
+
580
+ my $blksize = ${*$ftp}{'net_ftp_blksize'};
581
+ local $\; # Just in case
582
+
583
+ while (1) {
584
+ last unless $len = $data->read($buf, $blksize);
585
+
586
+ if (EBCDIC && $ftp->type ne 'I') {
587
+ $buf = $ftp->toebcdic($buf);
588
+ $len = length($buf);
589
+ }
590
+
591
+ if ($hashh) {
592
+ $count += $len;
593
+ print $hashh "#" x (int($count / $hashb));
594
+ $count %= $hashb;
595
+ }
596
+ unless (print $loc $buf) {
597
+ carp "Cannot write to Local file $local: $!\n";
598
+ $data->abort;
599
+ close($loc)
600
+ unless $localfd;
601
+ return;
602
+ }
603
+ }
604
+
605
+ print $hashh "\n" if $hashh;
606
+
607
+ unless ($localfd) {
608
+ unless (close($loc)) {
609
+ carp "Cannot close file $local (perhaps disk space) $!\n";
610
+ return;
611
+ }
612
+ }
613
+
614
+ unless ($data->close()) # implied $ftp->response
615
+ {
616
+ carp "Unable to close datastream";
617
+ return;
618
+ }
619
+
620
+ return $local;
621
+ }
622
+
623
+
624
+ sub cwd {
625
+ @_ == 1 || @_ == 2 or croak 'usage: $ftp->cwd([$dir])';
626
+
627
+ my ($ftp, $dir) = @_;
628
+
629
+ $dir = "/" unless defined($dir) && $dir =~ /\S/;
630
+
631
+ $dir eq ".."
632
+ ? $ftp->_CDUP()
633
+ : $ftp->_CWD($dir);
634
+ }
635
+
636
+
637
+ sub cdup {
638
+ @_ == 1 or croak 'usage: $ftp->cdup()';
639
+ $_[0]->_CDUP;
640
+ }
641
+
642
+
643
+ sub pwd {
644
+ @_ == 1 || croak 'usage: $ftp->pwd()';
645
+ my $ftp = shift;
646
+
647
+ $ftp->_PWD();
648
+ $ftp->_extract_path;
649
+ }
650
+
651
+ # rmdir( $ftp, $dir, [ $recurse ] )
652
+ #
653
+ # Removes $dir on remote host via FTP.
654
+ # $ftp is handle for remote host
655
+ #
656
+ # If $recurse is TRUE, the directory and deleted recursively.
657
+ # This means all of its contents and subdirectories.
658
+ #
659
+ # Initial version contributed by Dinkum Software
660
+ #
661
+ sub rmdir {
662
+ @_ == 2 || @_ == 3 or croak('usage: $ftp->rmdir($dir[, $recurse])');
663
+
664
+ # Pick off the args
665
+ my ($ftp, $dir, $recurse) = @_;
666
+ my $ok;
667
+
668
+ return $ok
669
+ if $ok = $ftp->_RMD($dir)
670
+ or !$recurse;
671
+
672
+ # Try to delete the contents
673
+ # Get a list of all the files in the directory, excluding the current and parent directories
674
+ my @filelist = map { /^(?:\S+;)+ (.+)$/ ? ($1) : () } grep { !/^(?:\S+;)*type=[cp]dir;/i } $ftp->_list_cmd("MLSD", $dir);
675
+
676
+ # Fallback to using the less well-defined NLST command if MLSD fails
677
+ @filelist = grep { !/^\.{1,2}$/ } $ftp->ls($dir)
678
+ unless @filelist;
679
+
680
+ return
681
+ unless @filelist; # failed, it is probably not a directory
682
+
683
+ return $ftp->delete($dir)
684
+ if @filelist == 1 and $dir eq $filelist[0];
685
+
686
+ # Go thru and delete each file or the directory
687
+ foreach my $file (map { m,/, ? $_ : "$dir/$_" } @filelist) {
688
+ next # successfully deleted the file
689
+ if $ftp->delete($file);
690
+
691
+ # Failed to delete it, assume its a directory
692
+ # Recurse and ignore errors, the final rmdir() will
693
+ # fail on any errors here
694
+ return $ok
695
+ unless $ok = $ftp->rmdir($file, 1);
696
+ }
697
+
698
+ # Directory should be empty
699
+ # Try to remove the directory again
700
+ # Pass results directly to caller
701
+ # If any of the prior deletes failed, this
702
+ # rmdir() will fail because directory is not empty
703
+ return $ftp->_RMD($dir);
704
+ }
705
+
706
+
707
+ sub restart {
708
+ @_ == 2 || croak 'usage: $ftp->restart($where)';
709
+
710
+ my ($ftp, $where) = @_;
711
+
712
+ ${*$ftp}{'net_ftp_rest'} = $where;
713
+
714
+ return;
715
+ }
716
+
717
+
718
+ sub mkdir {
719
+ @_ == 2 || @_ == 3 or croak 'usage: $ftp->mkdir($dir[, $recurse])';
720
+
721
+ my ($ftp, $dir, $recurse) = @_;
722
+
723
+ $ftp->_MKD($dir) || $recurse
724
+ or return;
725
+
726
+ my $path = $dir;
727
+
728
+ unless ($ftp->ok) {
729
+ my @path = split(m#(?=/+)#, $dir);
730
+
731
+ $path = "";
732
+
733
+ while (@path) {
734
+ $path .= shift @path;
735
+
736
+ $ftp->_MKD($path);
737
+
738
+ $path = $ftp->_extract_path($path);
739
+ }
740
+
741
+ # If the creation of the last element was not successful, see if we
742
+ # can cd to it, if so then return path
743
+
744
+ unless ($ftp->ok) {
745
+ my ($status, $message) = ($ftp->status, $ftp->message);
746
+ my $pwd = $ftp->pwd;
747
+
748
+ if ($pwd && $ftp->cwd($dir)) {
749
+ $path = $dir;
750
+ $ftp->cwd($pwd);
751
+ }
752
+ else {
753
+ undef $path;
754
+ }
755
+ $ftp->set_status($status, $message);
756
+ }
757
+ }
758
+
759
+ $path;
760
+ }
761
+
762
+
763
+ sub delete {
764
+ @_ == 2 || croak 'usage: $ftp->delete($filename)';
765
+
766
+ $_[0]->_DELE($_[1]);
767
+ }
768
+
769
+
770
+ sub put { shift->_store_cmd("stor", @_) }
771
+ sub put_unique { shift->_store_cmd("stou", @_) }
772
+ sub append { shift->_store_cmd("appe", @_) }
773
+
774
+
775
+ sub nlst { shift->_data_cmd("NLST", @_) }
776
+ sub list { shift->_data_cmd("LIST", @_) }
777
+ sub retr { shift->_data_cmd("RETR", @_) }
778
+ sub stor { shift->_data_cmd("STOR", @_) }
779
+ sub stou { shift->_data_cmd("STOU", @_) }
780
+ sub appe { shift->_data_cmd("APPE", @_) }
781
+
782
+
783
+ sub _store_cmd {
784
+ my ($ftp, $cmd, $local, $remote) = @_;
785
+ my ($loc, $sock, $len, $buf);
786
+ local *FD;
787
+
788
+ my $localfd = ref($local) || ref(\$local) eq "GLOB";
789
+
790
+ if (!defined($remote) and 'STOU' ne uc($cmd)) {
791
+ croak 'Must specify remote filename with stream input'
792
+ if $localfd;
793
+
794
+ require File::Basename;
795
+ $remote = File::Basename::basename($local);
796
+ }
797
+ if (defined ${*$ftp}{'net_ftp_allo'}) {
798
+ delete ${*$ftp}{'net_ftp_allo'};
799
+ }
800
+ else {
801
+
802
+ # if the user hasn't already invoked the alloc method since the last
803
+ # _store_cmd call, figure out if the local file is a regular file(not
804
+ # a pipe, or device) and if so get the file size from stat, and send
805
+ # an ALLO command before sending the STOR, STOU, or APPE command.
806
+ my $size = do { local $^W; -f $local && -s _ }; # no ALLO if sending data from a pipe
807
+ ${*$ftp}{'net_ftp_allo'} = $size if $size;
808
+ }
809
+ croak("Bad remote filename '$remote'\n")
810
+ if defined($remote) and $remote =~ /[\r\n]/s;
811
+
812
+ if ($localfd) {
813
+ $loc = $local;
814
+ }
815
+ else {
816
+ $loc = \*FD;
817
+
818
+ unless (sysopen($loc, $local, O_RDONLY)) {
819
+ carp "Cannot open Local file $local: $!\n";
820
+ return;
821
+ }
822
+ }
823
+
824
+ if ($ftp->type eq 'I' && !binmode($loc)) {
825
+ carp "Cannot binmode Local file $local: $!\n";
826
+ return;
827
+ }
828
+
829
+ delete ${*$ftp}{'net_ftp_port'};
830
+ delete ${*$ftp}{'net_ftp_pasv'};
831
+
832
+ $sock = $ftp->_data_cmd($cmd, grep { defined } $remote)
833
+ or return;
834
+
835
+ $remote = ($ftp->message =~ /\w+\s*:\s*(.*)/)[0]
836
+ if 'STOU' eq uc $cmd;
837
+
838
+ my $blksize = ${*$ftp}{'net_ftp_blksize'};
839
+
840
+ my ($count, $hashh, $hashb, $ref) = (0);
841
+
842
+ ($hashh, $hashb) = @$ref
843
+ if ($ref = ${*$ftp}{'net_ftp_hash'});
844
+
845
+ while (1) {
846
+ last unless $len = read($loc, $buf = "", $blksize);
847
+
848
+ if (EBCDIC && $ftp->type ne 'I') {
849
+ $buf = $ftp->toascii($buf);
850
+ $len = length($buf);
851
+ }
852
+
853
+ if ($hashh) {
854
+ $count += $len;
855
+ print $hashh "#" x (int($count / $hashb));
856
+ $count %= $hashb;
857
+ }
858
+
859
+ my $wlen;
860
+ unless (defined($wlen = $sock->write($buf, $len)) && $wlen == $len) {
861
+ $sock->abort;
862
+ close($loc)
863
+ unless $localfd;
864
+ print $hashh "\n" if $hashh;
865
+ return;
866
+ }
867
+ }
868
+
869
+ print $hashh "\n" if $hashh;
870
+
871
+ close($loc)
872
+ unless $localfd;
873
+
874
+ $sock->close()
875
+ or return;
876
+
877
+ if ('STOU' eq uc $cmd and $ftp->message =~ m/unique\s+file\s*name\s*:\s*(.*)\)|"(.*)"/) {
878
+ require File::Basename;
879
+ $remote = File::Basename::basename($+);
880
+ }
881
+
882
+ return $remote;
883
+ }
884
+
885
+
886
+ sub port {
887
+ @_ == 1 || @_ == 2 or croak 'usage: $self->port([$port])';
888
+ return _eprt('PORT',@_);
889
+ }
890
+
891
+ sub eprt {
892
+ @_ == 1 || @_ == 2 or croak 'usage: $self->eprt([$port])';
893
+ return _eprt('EPRT',@_);
894
+ }
895
+
896
+ sub _eprt {
897
+ my ($cmd,$ftp,$port) = @_;
898
+ delete ${*$ftp}{net_ftp_intern_port};
899
+ unless ($port) {
900
+ my $listen = ${*$ftp}{net_ftp_listen} ||= $IOCLASS->new(
901
+ Listen => 1,
902
+ Timeout => $ftp->timeout,
903
+ LocalAddr => $ftp->sockhost,
904
+ $family_key => $ftp->sockdomain,
905
+ can_ssl() ? (
906
+ %{ ${*$ftp}{net_ftp_tlsargs} },
907
+ SSL_startHandshake => 0,
908
+ ):(),
909
+ );
910
+ ${*$ftp}{net_ftp_intern_port} = 1;
911
+ my $fam = ($listen->sockdomain == AF_INET) ? 1:2;
912
+ if ( $cmd eq 'EPRT' || $fam == 2 ) {
913
+ $port = "|$fam|".$listen->sockhost."|".$listen->sockport."|";
914
+ $cmd = 'EPRT';
915
+ } else {
916
+ my $p = $listen->sockport;
917
+ $port = join(',',split(m{\.},$listen->sockhost),$p >> 8,$p & 0xff);
918
+ }
919
+ } elsif (ref($port) eq 'ARRAY') {
920
+ $port = join(',',split(m{\.},@$port[0]),@$port[1] >> 8,@$port[1] & 0xff);
921
+ }
922
+ my $ok = $cmd eq 'EPRT' ? $ftp->_EPRT($port) : $ftp->_PORT($port);
923
+ ${*$ftp}{net_ftp_port} = $port if $ok;
924
+ return $ok;
925
+ }
926
+
927
+
928
+ sub ls { shift->_list_cmd("NLST", @_); }
929
+ sub dir { shift->_list_cmd("LIST", @_); }
930
+
931
+
932
+ sub pasv {
933
+ my $ftp = shift;
934
+ @_ and croak 'usage: $ftp->port()';
935
+ return $ftp->epsv if $ftp->sockdomain != AF_INET;
936
+ delete ${*$ftp}{net_ftp_intern_port};
937
+
938
+ if ( $ftp->_PASV &&
939
+ $ftp->message =~ m{(\d+,\d+,\d+,\d+),(\d+),(\d+)} ) {
940
+ my $port = 256 * $2 + $3;
941
+ ( my $ip = $1 ) =~s{,}{.}g;
942
+ return ${*$ftp}{net_ftp_pasv} = [ $ip,$port ];
943
+ }
944
+ return;
945
+ }
946
+
947
+ sub epsv {
948
+ my $ftp = shift;
949
+ @_ and croak 'usage: $ftp->epsv()';
950
+ delete ${*$ftp}{net_ftp_intern_port};
951
+
952
+ $ftp->_EPSV && $ftp->message =~ m{\(([\x33-\x7e])\1\1(\d+)\1\)}
953
+ ? ${*$ftp}{net_ftp_pasv} = [ $ftp->peerhost, $2 ]
954
+ : undef;
955
+ }
956
+
957
+
958
+ sub unique_name {
959
+ my $ftp = shift;
960
+ ${*$ftp}{'net_ftp_unique'} || undef;
961
+ }
962
+
963
+
964
+ sub supported {
965
+ @_ == 2 or croak 'usage: $ftp->supported($cmd)';
966
+ my $ftp = shift;
967
+ my $cmd = uc shift;
968
+ my $hash = ${*$ftp}{'net_ftp_supported'} ||= {};
969
+
970
+ return $hash->{$cmd}
971
+ if exists $hash->{$cmd};
972
+
973
+ return $hash->{$cmd} = 1
974
+ if $ftp->feature($cmd);
975
+
976
+ return $hash->{$cmd} = 0
977
+ unless $ftp->_HELP($cmd);
978
+
979
+ my $text = $ftp->message;
980
+ if ($text =~ /following.+commands/i) {
981
+ $text =~ s/^.*\n//;
982
+ while ($text =~ /(\*?)(\w+)(\*?)/sg) {
983
+ $hash->{"\U$2"} = !length("$1$3");
984
+ }
985
+ }
986
+ else {
987
+ $hash->{$cmd} = $text !~ /unimplemented/i;
988
+ }
989
+
990
+ $hash->{$cmd} ||= 0;
991
+ }
992
+
993
+ ##
994
+ ## Deprecated methods
995
+ ##
996
+
997
+
998
+ sub lsl {
999
+ carp "Use of Net::FTP::lsl deprecated, use 'dir'"
1000
+ if $^W;
1001
+ goto &dir;
1002
+ }
1003
+
1004
+
1005
+ sub authorise {
1006
+ carp "Use of Net::FTP::authorise deprecated, use 'authorize'"
1007
+ if $^W;
1008
+ goto &authorize;
1009
+ }
1010
+
1011
+
1012
+ ##
1013
+ ## Private methods
1014
+ ##
1015
+
1016
+
1017
+ sub _extract_path {
1018
+ my ($ftp, $path) = @_;
1019
+
1020
+ # This tries to work both with and without the quote doubling
1021
+ # convention (RFC 959 requires it, but the first 3 servers I checked
1022
+ # didn't implement it). It will fail on a server which uses a quote in
1023
+ # the message which isn't a part of or surrounding the path.
1024
+ $ftp->ok
1025
+ && $ftp->message =~ /(?:^|\s)\"(.*)\"(?:$|\s)/
1026
+ && ($path = $1) =~ s/\"\"/\"/g;
1027
+
1028
+ $path;
1029
+ }
1030
+
1031
+ ##
1032
+ ## Communication methods
1033
+ ##
1034
+
1035
+
1036
+ sub _dataconn {
1037
+ my $ftp = shift;
1038
+ my $pkg = "Net::FTP::" . $ftp->type;
1039
+ eval "require " . $pkg ## no critic (BuiltinFunctions::ProhibitStringyEval)
1040
+ or croak("cannot load $pkg required for type ".$ftp->type);
1041
+ $pkg =~ s/ /_/g;
1042
+ delete ${*$ftp}{net_ftp_dataconn};
1043
+
1044
+ my $conn;
1045
+ my $pasv = ${*$ftp}{net_ftp_pasv};
1046
+ if ($pasv) {
1047
+ $conn = $pkg->new(
1048
+ PeerAddr => $pasv->[0],
1049
+ PeerPort => $pasv->[1],
1050
+ LocalAddr => ${*$ftp}{net_ftp_localaddr},
1051
+ $family_key => ${*$ftp}{net_ftp_domain},
1052
+ Timeout => $ftp->timeout,
1053
+ can_ssl() ? (
1054
+ SSL_startHandshake => 0,
1055
+ %{${*$ftp}{net_ftp_tlsargs}},
1056
+ ):(),
1057
+ ) or return;
1058
+ } elsif (my $listen = delete ${*$ftp}{net_ftp_listen}) {
1059
+ $conn = $listen->accept($pkg) or return;
1060
+ $conn->timeout($ftp->timeout);
1061
+ close($listen);
1062
+ } else {
1063
+ croak("no listener in active mode");
1064
+ }
1065
+
1066
+ if (( ${*$ftp}{net_ftp_tlsprot} || '') eq 'P') {
1067
+ if ($conn->connect_SSL) {
1068
+ # SSL handshake ok
1069
+ } else {
1070
+ carp("failed to ssl upgrade dataconn: $IO::Socket::SSL::SSL_ERROR");
1071
+ return;
1072
+ }
1073
+ }
1074
+
1075
+ ${*$ftp}{net_ftp_dataconn} = $conn;
1076
+ ${*$conn} = "";
1077
+ ${*$conn}{net_ftp_cmd} = $ftp;
1078
+ ${*$conn}{net_ftp_blksize} = ${*$ftp}{net_ftp_blksize};
1079
+ return $conn;
1080
+ }
1081
+
1082
+
1083
+ sub _list_cmd {
1084
+ my $ftp = shift;
1085
+ my $cmd = uc shift;
1086
+
1087
+ delete ${*$ftp}{'net_ftp_port'};
1088
+ delete ${*$ftp}{'net_ftp_pasv'};
1089
+
1090
+ my $data = $ftp->_data_cmd($cmd, @_);
1091
+
1092
+ return
1093
+ unless (defined $data);
1094
+
1095
+ require Net::FTP::A;
1096
+ bless $data, "Net::FTP::A"; # Force ASCII mode
1097
+
1098
+ my $databuf = '';
1099
+ my $buf = '';
1100
+ my $blksize = ${*$ftp}{'net_ftp_blksize'};
1101
+
1102
+ while ($data->read($databuf, $blksize)) {
1103
+ $buf .= $databuf;
1104
+ }
1105
+
1106
+ my $list = [split(/\n/, $buf)];
1107
+
1108
+ $data->close();
1109
+
1110
+ if (EBCDIC) {
1111
+ for (@$list) { $_ = $ftp->toebcdic($_) }
1112
+ }
1113
+
1114
+ wantarray
1115
+ ? @{$list}
1116
+ : $list;
1117
+ }
1118
+
1119
+
1120
+ sub _data_cmd {
1121
+ my $ftp = shift;
1122
+ my $cmd = uc shift;
1123
+ my $ok = 1;
1124
+ my $where = delete ${*$ftp}{'net_ftp_rest'} || 0;
1125
+ my $arg;
1126
+
1127
+ for my $arg (@_) {
1128
+ croak("Bad argument '$arg'\n")
1129
+ if $arg =~ /[\r\n]/s;
1130
+ }
1131
+
1132
+ if ( ${*$ftp}{'net_ftp_passive'}
1133
+ && !defined ${*$ftp}{'net_ftp_pasv'}
1134
+ && !defined ${*$ftp}{'net_ftp_port'})
1135
+ {
1136
+ return unless defined $ftp->pasv;
1137
+
1138
+ if ($where and !$ftp->_REST($where)) {
1139
+ my ($status, $message) = ($ftp->status, $ftp->message);
1140
+ $ftp->abort;
1141
+ $ftp->set_status($status, $message);
1142
+ return;
1143
+ }
1144
+
1145
+ # first send command, then open data connection
1146
+ # otherwise the peer might not do a full accept (with SSL
1147
+ # handshake if PROT P)
1148
+ $ftp->command($cmd, @_);
1149
+ my $data = $ftp->_dataconn();
1150
+ if (CMD_INFO == $ftp->response()) {
1151
+ $data->reading
1152
+ if $data && $cmd =~ /RETR|LIST|NLST|MLSD/;
1153
+ return $data;
1154
+ }
1155
+ $data->_close if $data;
1156
+
1157
+ return;
1158
+ }
1159
+
1160
+ $ok = $ftp->port
1161
+ unless (defined ${*$ftp}{'net_ftp_port'}
1162
+ || defined ${*$ftp}{'net_ftp_pasv'});
1163
+
1164
+ $ok = $ftp->_REST($where)
1165
+ if $ok && $where;
1166
+
1167
+ return
1168
+ unless $ok;
1169
+
1170
+ if ($cmd =~ /(STOR|APPE|STOU)/ and exists ${*$ftp}{net_ftp_allo} and
1171
+ $ftp->supported("ALLO"))
1172
+ {
1173
+ $ftp->_ALLO(delete ${*$ftp}{net_ftp_allo})
1174
+ or return;
1175
+ }
1176
+
1177
+ $ftp->command($cmd, @_);
1178
+
1179
+ return 1
1180
+ if (defined ${*$ftp}{'net_ftp_pasv'});
1181
+
1182
+ $ok = CMD_INFO == $ftp->response();
1183
+
1184
+ return $ok
1185
+ unless exists ${*$ftp}{'net_ftp_intern_port'};
1186
+
1187
+ if ($ok) {
1188
+ my $data = $ftp->_dataconn();
1189
+
1190
+ $data->reading
1191
+ if $data && $cmd =~ /RETR|LIST|NLST|MLSD/;
1192
+
1193
+ return $data;
1194
+ }
1195
+
1196
+
1197
+ close(delete ${*$ftp}{'net_ftp_listen'});
1198
+
1199
+ return;
1200
+ }
1201
+
1202
+ ##
1203
+ ## Over-ride methods (Net::Cmd)
1204
+ ##
1205
+
1206
+
1207
+ sub debug_text { $_[2] =~ /^(pass|resp|acct)/i ? "$1 ....\n" : $_[2]; }
1208
+
1209
+
1210
+ sub command {
1211
+ my $ftp = shift;
1212
+
1213
+ delete ${*$ftp}{'net_ftp_port'};
1214
+ $ftp->SUPER::command(@_);
1215
+ }
1216
+
1217
+
1218
+ sub response {
1219
+ my $ftp = shift;
1220
+ my $code = $ftp->SUPER::response() || 5; # assume 500 if undef
1221
+
1222
+ delete ${*$ftp}{'net_ftp_pasv'}
1223
+ if ($code != CMD_MORE && $code != CMD_INFO);
1224
+
1225
+ $code;
1226
+ }
1227
+
1228
+
1229
+ sub parse_response {
1230
+ return ($1, $2 eq "-")
1231
+ if $_[1] =~ s/^(\d\d\d)([- ]?)//o;
1232
+
1233
+ my $ftp = shift;
1234
+
1235
+ # Darn MS FTP server is a load of CRAP !!!!
1236
+ # Expect to see undef here.
1237
+ return ()
1238
+ unless 0 + (${*$ftp}{'net_cmd_code'} || 0);
1239
+
1240
+ (${*$ftp}{'net_cmd_code'}, 1);
1241
+ }
1242
+
1243
+ ##
1244
+ ## Allow 2 servers to talk directly
1245
+ ##
1246
+
1247
+
1248
+ sub pasv_xfer_unique {
1249
+ my ($sftp, $sfile, $dftp, $dfile) = @_;
1250
+ $sftp->pasv_xfer($sfile, $dftp, $dfile, 1);
1251
+ }
1252
+
1253
+
1254
+ sub pasv_xfer {
1255
+ my ($sftp, $sfile, $dftp, $dfile, $unique) = @_;
1256
+
1257
+ ($dfile = $sfile) =~ s#.*/##
1258
+ unless (defined $dfile);
1259
+
1260
+ my $port = $sftp->pasv
1261
+ or return;
1262
+
1263
+ $dftp->port($port)
1264
+ or return;
1265
+
1266
+ return
1267
+ unless ($unique ? $dftp->stou($dfile) : $dftp->stor($dfile));
1268
+
1269
+ unless ($sftp->retr($sfile) && $sftp->response == CMD_INFO) {
1270
+ $sftp->retr($sfile);
1271
+ $dftp->abort;
1272
+ $dftp->response();
1273
+ return;
1274
+ }
1275
+
1276
+ $dftp->pasv_wait($sftp);
1277
+ }
1278
+
1279
+
1280
+ sub pasv_wait {
1281
+ @_ == 2 or croak 'usage: $ftp->pasv_wait($non_pasv_server)';
1282
+
1283
+ my ($ftp, $non_pasv_server) = @_;
1284
+ my ($file, $rin, $rout);
1285
+
1286
+ vec($rin = '', fileno($ftp), 1) = 1;
1287
+ select($rout = $rin, undef, undef, undef);
1288
+
1289
+ my $dres = $ftp->response();
1290
+ my $sres = $non_pasv_server->response();
1291
+
1292
+ return
1293
+ unless $dres == CMD_OK && $sres == CMD_OK;
1294
+
1295
+ return
1296
+ unless $ftp->ok() && $non_pasv_server->ok();
1297
+
1298
+ return $1
1299
+ if $ftp->message =~ /unique file name:\s*(\S*)\s*\)/;
1300
+
1301
+ return $1
1302
+ if $non_pasv_server->message =~ /unique file name:\s*(\S*)\s*\)/;
1303
+
1304
+ return 1;
1305
+ }
1306
+
1307
+
1308
+ sub feature {
1309
+ @_ == 2 or croak 'usage: $ftp->feature($name)';
1310
+ my ($ftp, $name) = @_;
1311
+
1312
+ my $feature = ${*$ftp}{net_ftp_feature} ||= do {
1313
+ my @feat;
1314
+
1315
+ # Example response
1316
+ # 211-Features:
1317
+ # MDTM
1318
+ # REST STREAM
1319
+ # SIZE
1320
+ # 211 End
1321
+
1322
+ @feat = map { /^\s+(.*\S)/ } $ftp->message
1323
+ if $ftp->_FEAT;
1324
+
1325
+ \@feat;
1326
+ };
1327
+
1328
+ return grep { /^\Q$name\E\b/i } @$feature;
1329
+ }
1330
+
1331
+
1332
+ sub cmd { shift->command(@_)->response() }
1333
+
1334
+ ########################################
1335
+ #
1336
+ # RFC959 + RFC2428 + RFC4217 commands
1337
+ #
1338
+
1339
+
1340
+ sub _ABOR { shift->command("ABOR")->response() == CMD_OK }
1341
+ sub _ALLO { shift->command("ALLO", @_)->response() == CMD_OK }
1342
+ sub _CDUP { shift->command("CDUP")->response() == CMD_OK }
1343
+ sub _NOOP { shift->command("NOOP")->response() == CMD_OK }
1344
+ sub _PASV { shift->command("PASV")->response() == CMD_OK }
1345
+ sub _QUIT { shift->command("QUIT")->response() == CMD_OK }
1346
+ sub _DELE { shift->command("DELE", @_)->response() == CMD_OK }
1347
+ sub _CWD { shift->command("CWD", @_)->response() == CMD_OK }
1348
+ sub _PORT { shift->command("PORT", @_)->response() == CMD_OK }
1349
+ sub _RMD { shift->command("RMD", @_)->response() == CMD_OK }
1350
+ sub _MKD { shift->command("MKD", @_)->response() == CMD_OK }
1351
+ sub _PWD { shift->command("PWD", @_)->response() == CMD_OK }
1352
+ sub _TYPE { shift->command("TYPE", @_)->response() == CMD_OK }
1353
+ sub _RNTO { shift->command("RNTO", @_)->response() == CMD_OK }
1354
+ sub _RESP { shift->command("RESP", @_)->response() == CMD_OK }
1355
+ sub _MDTM { shift->command("MDTM", @_)->response() == CMD_OK }
1356
+ sub _SIZE { shift->command("SIZE", @_)->response() == CMD_OK }
1357
+ sub _HELP { shift->command("HELP", @_)->response() == CMD_OK }
1358
+ sub _STAT { shift->command("STAT", @_)->response() == CMD_OK }
1359
+ sub _FEAT { shift->command("FEAT", @_)->response() == CMD_OK }
1360
+ sub _PBSZ { shift->command("PBSZ", @_)->response() == CMD_OK }
1361
+ sub _PROT { shift->command("PROT", @_)->response() == CMD_OK }
1362
+ sub _CCC { shift->command("CCC", @_)->response() == CMD_OK }
1363
+ sub _EPRT { shift->command("EPRT", @_)->response() == CMD_OK }
1364
+ sub _EPSV { shift->command("EPSV", @_)->response() == CMD_OK }
1365
+ sub _APPE { shift->command("APPE", @_)->response() == CMD_INFO }
1366
+ sub _LIST { shift->command("LIST", @_)->response() == CMD_INFO }
1367
+ sub _NLST { shift->command("NLST", @_)->response() == CMD_INFO }
1368
+ sub _RETR { shift->command("RETR", @_)->response() == CMD_INFO }
1369
+ sub _STOR { shift->command("STOR", @_)->response() == CMD_INFO }
1370
+ sub _STOU { shift->command("STOU", @_)->response() == CMD_INFO }
1371
+ sub _RNFR { shift->command("RNFR", @_)->response() == CMD_MORE }
1372
+ sub _REST { shift->command("REST", @_)->response() == CMD_MORE }
1373
+ sub _PASS { shift->command("PASS", @_)->response() }
1374
+ sub _ACCT { shift->command("ACCT", @_)->response() }
1375
+ sub _AUTH { shift->command("AUTH", @_)->response() }
1376
+
1377
+
1378
+ sub _USER {
1379
+ my $ftp = shift;
1380
+ my $ok = $ftp->command("USER", @_)->response();
1381
+
1382
+ # A certain brain dead firewall :-)
1383
+ $ok = $ftp->command("user", @_)->response()
1384
+ unless $ok == CMD_MORE or $ok == CMD_OK;
1385
+
1386
+ $ok;
1387
+ }
1388
+
1389
+
1390
+ sub _SMNT { shift->unsupported(@_) }
1391
+ sub _MODE { shift->unsupported(@_) }
1392
+ sub _SYST { shift->unsupported(@_) }
1393
+ sub _STRU { shift->unsupported(@_) }
1394
+ sub _REIN { shift->unsupported(@_) }
1395
+
1396
+
1397
+ 1;
1398
+
1399
+ __END__
1400
+
1401
+ =head1 NAME
1402
+
1403
+ Net::FTP - FTP Client class
1404
+
1405
+ =head1 SYNOPSIS
1406
+
1407
+ use Net::FTP;
1408
+
1409
+ $ftp = Net::FTP->new("some.host.name", Debug => 0)
1410
+ or die "Cannot connect to some.host.name: $@";
1411
+
1412
+ $ftp->login("anonymous",'-anonymous@')
1413
+ or die "Cannot login ", $ftp->message;
1414
+
1415
+ $ftp->cwd("/pub")
1416
+ or die "Cannot change working directory ", $ftp->message;
1417
+
1418
+ $ftp->get("that.file")
1419
+ or die "get failed ", $ftp->message;
1420
+
1421
+ $ftp->quit;
1422
+
1423
+ =head1 DESCRIPTION
1424
+
1425
+ C<Net::FTP> is a class implementing a simple FTP client in Perl as
1426
+ described in RFC959. It provides wrappers for the commonly used subset of the
1427
+ RFC959 commands.
1428
+ If L<IO::Socket::IP> or L<IO::Socket::INET6> is installed it also provides
1429
+ support for IPv6 as defined in RFC2428.
1430
+ And with L<IO::Socket::SSL> installed it provides support for implicit FTPS
1431
+ and explicit FTPS as defined in RFC4217.
1432
+
1433
+ The Net::FTP class is a subclass of Net::Cmd and (depending on avaibility) of
1434
+ IO::Socket::IP, IO::Socket::INET6 or IO::Socket::INET.
1435
+
1436
+ =head2 Overview
1437
+
1438
+ FTP stands for File Transfer Protocol. It is a way of transferring
1439
+ files between networked machines. The protocol defines a client
1440
+ (whose commands are provided by this module) and a server (not
1441
+ implemented in this module). Communication is always initiated by the
1442
+ client, and the server responds with a message and a status code (and
1443
+ sometimes with data).
1444
+
1445
+ The FTP protocol allows files to be sent to or fetched from the
1446
+ server. Each transfer involves a B<local file> (on the client) and a
1447
+ B<remote file> (on the server). In this module, the same file name
1448
+ will be used for both local and remote if only one is specified. This
1449
+ means that transferring remote file C</path/to/file> will try to put
1450
+ that file in C</path/to/file> locally, unless you specify a local file
1451
+ name.
1452
+
1453
+ The protocol also defines several standard B<translations> which the
1454
+ file can undergo during transfer. These are ASCII, EBCDIC, binary,
1455
+ and byte. ASCII is the default type, and indicates that the sender of
1456
+ files will translate the ends of lines to a standard representation
1457
+ which the receiver will then translate back into their local
1458
+ representation. EBCDIC indicates the file being transferred is in
1459
+ EBCDIC format. Binary (also known as image) format sends the data as
1460
+ a contiguous bit stream. Byte format transfers the data as bytes, the
1461
+ values of which remain the same regardless of differences in byte size
1462
+ between the two machines (in theory - in practice you should only use
1463
+ this if you really know what you're doing). This class does not support
1464
+ the EBCDIC or byte formats, and will default to binary instead if they
1465
+ are attempted.
1466
+
1467
+ =head2 Class Methods
1468
+
1469
+ =over 4
1470
+
1471
+ =item C<new([$host][, %options])>
1472
+
1473
+ This is the constructor for a new Net::FTP object. C<$host> is the
1474
+ name of the remote host to which an FTP connection is required.
1475
+
1476
+ C<$host> is optional. If C<$host> is not given then it may instead be
1477
+ passed as the C<Host> option described below.
1478
+
1479
+ C<%options> are passed in a hash like fashion, using key and value pairs.
1480
+ Possible options are:
1481
+
1482
+ B<Host> - FTP host to connect to. It may be a single scalar, as defined for
1483
+ the C<PeerAddr> option in L<IO::Socket::INET>, or a reference to
1484
+ an array with hosts to try in turn. The L</host> method will return the value
1485
+ which was used to connect to the host.
1486
+
1487
+ B<Firewall> - The name of a machine which acts as an FTP firewall. This can be
1488
+ overridden by an environment variable C<FTP_FIREWALL>. If specified, and the
1489
+ given host cannot be directly connected to, then the
1490
+ connection is made to the firewall machine and the string C<@hostname> is
1491
+ appended to the login identifier. This kind of setup is also referred to
1492
+ as an ftp proxy.
1493
+
1494
+ B<FirewallType> - The type of firewall running on the machine indicated by
1495
+ B<Firewall>. This can be overridden by an environment variable
1496
+ C<FTP_FIREWALL_TYPE>. For a list of permissible types, see the description of
1497
+ ftp_firewall_type in L<Net::Config>.
1498
+
1499
+ B<BlockSize> - This is the block size that Net::FTP will use when doing
1500
+ transfers. (defaults to 10240)
1501
+
1502
+ B<Port> - The port number to connect to on the remote machine for the
1503
+ FTP connection
1504
+
1505
+ B<SSL> - If the connection should be done from start with SSL, contrary to later
1506
+ upgrade with C<starttls>.
1507
+
1508
+ B<SSL_*> - SSL arguments which will be applied when upgrading the control or
1509
+ data connection to SSL. You can use SSL arguments as documented in
1510
+ L<IO::Socket::SSL>, but it will usually use the right arguments already.
1511
+
1512
+ B<Timeout> - Set a timeout value in seconds (defaults to 120)
1513
+
1514
+ B<Debug> - debug level (see the debug method in L<Net::Cmd>)
1515
+
1516
+ B<Passive> - If set to a non-zero value then all data transfers will
1517
+ be done using passive mode. If set to zero then data transfers will be
1518
+ done using active mode. If the machine is connected to the Internet
1519
+ directly, both passive and active mode should work equally well.
1520
+ Behind most firewall and NAT configurations passive mode has a better
1521
+ chance of working. However, in some rare firewall configurations,
1522
+ active mode actually works when passive mode doesn't. Some really old
1523
+ FTP servers might not implement passive transfers. If not specified,
1524
+ then the transfer mode is set by the environment variable
1525
+ C<FTP_PASSIVE> or if that one is not set by the settings done by the
1526
+ F<libnetcfg> utility. If none of these apply then passive mode is
1527
+ used.
1528
+
1529
+ B<Hash> - If given a reference to a file handle (e.g., C<\*STDERR>),
1530
+ print hash marks (#) on that filehandle every 1024 bytes. This
1531
+ simply invokes the C<hash()> method for you, so that hash marks
1532
+ are displayed for all transfers. You can, of course, call C<hash()>
1533
+ explicitly whenever you'd like.
1534
+
1535
+ B<LocalAddr> - Local address to use for all socket connections. This
1536
+ argument will be passed to the super class, i.e. L<IO::Socket::INET>
1537
+ or L<IO::Socket::IP>.
1538
+
1539
+ B<Domain> - Domain to use, i.e. AF_INET or AF_INET6. This
1540
+ argument will be passed to the IO::Socket super class.
1541
+ This can be used to enforce IPv4 even with L<IO::Socket::IP>
1542
+ which would default to IPv6.
1543
+ B<Family> is accepted as alternative name for B<Domain>.
1544
+
1545
+ If the constructor fails undef will be returned and an error message will
1546
+ be in $@
1547
+
1548
+ =back
1549
+
1550
+ =head2 Object Methods
1551
+
1552
+ Unless otherwise stated all methods return either a I<true> or I<false>
1553
+ value, with I<true> meaning that the operation was a success. When a method
1554
+ states that it returns a value, failure will be returned as I<undef> or an
1555
+ empty list.
1556
+
1557
+ C<Net::FTP> inherits from C<Net::Cmd> so methods defined in C<Net::Cmd> may
1558
+ be used to send commands to the remote FTP server in addition to the methods
1559
+ documented here.
1560
+
1561
+ =over 4
1562
+
1563
+ =item C<login([$login[, $password[, $account]]])>
1564
+
1565
+ Log into the remote FTP server with the given login information. If
1566
+ no arguments are given then the C<Net::FTP> uses the C<Net::Netrc>
1567
+ package to lookup the login information for the connected host.
1568
+ If no information is found then a login of I<anonymous> is used.
1569
+ If no password is given and the login is I<anonymous> then I<anonymous@>
1570
+ will be used for password.
1571
+
1572
+ If the connection is via a firewall then the C<authorize> method will
1573
+ be called with no arguments.
1574
+
1575
+ =item C<starttls()>
1576
+
1577
+ Upgrade existing plain connection to SSL.
1578
+ The SSL arguments have to be given in C<new> already because they are needed for
1579
+ data connections too.
1580
+
1581
+ =item C<stoptls()>
1582
+
1583
+ Downgrade existing SSL connection back to plain.
1584
+ This is needed to work with some FTP helpers at firewalls, which need to see the
1585
+ PORT and PASV commands and responses to dynamically open the necessary ports.
1586
+ In this case C<starttls> is usually only done to protect the authorization.
1587
+
1588
+ =item C<prot($level)>
1589
+
1590
+ Set what type of data channel protection the client and server will be using.
1591
+ Only C<$level>s "C" (clear) and "P" (private) are supported.
1592
+
1593
+ =item C<host()>
1594
+
1595
+ Returns the value used by the constructor, and passed to the IO::Socket super
1596
+ class to connect to the host.
1597
+
1598
+ =item C<account($acct)>
1599
+
1600
+ Set a string identifying the user's account.
1601
+
1602
+ =item C<authorize([$auth[, $resp]])>
1603
+
1604
+ This is a protocol used by some firewall ftp proxies. It is used
1605
+ to authorise the user to send data out. If both arguments are not specified
1606
+ then C<authorize> uses C<Net::Netrc> to do a lookup.
1607
+
1608
+ =item C<site($args)>
1609
+
1610
+ Send a SITE command to the remote server and wait for a response.
1611
+
1612
+ Returns most significant digit of the response code.
1613
+
1614
+ =item C<ascii()>
1615
+
1616
+ Transfer file in ASCII. CRLF translation will be done if required
1617
+
1618
+ =item C<binary()>
1619
+
1620
+ Transfer file in binary mode. No transformation will be done.
1621
+
1622
+ B<Hint>: If both server and client machines use the same line ending for
1623
+ text files, then it will be faster to transfer all files in binary mode.
1624
+
1625
+ =item C<type([$type])>
1626
+
1627
+ Set or get if files will be transferred in ASCII or binary mode.
1628
+
1629
+ =item C<rename($oldname, $newname)>
1630
+
1631
+ Rename a file on the remote FTP server from C<$oldname> to C<$newname>. This
1632
+ is done by sending the RNFR and RNTO commands.
1633
+
1634
+ =item C<delete($filename)>
1635
+
1636
+ Send a request to the server to delete C<$filename>.
1637
+
1638
+ =item C<cwd([$dir])>
1639
+
1640
+ Attempt to change directory to the directory given in C<$dir>. If
1641
+ C<$dir> is C<"..">, the FTP C<CDUP> command is used to attempt to
1642
+ move up one directory. If no directory is given then an attempt is made
1643
+ to change the directory to the root directory.
1644
+
1645
+ =item C<cdup()>
1646
+
1647
+ Change directory to the parent of the current directory.
1648
+
1649
+ =item C<passive([$passive])>
1650
+
1651
+ Set or get if data connections will be initiated in passive mode.
1652
+
1653
+ =item C<pwd()>
1654
+
1655
+ Returns the full pathname of the current directory.
1656
+
1657
+ =item C<restart($where)>
1658
+
1659
+ Set the byte offset at which to begin the next data transfer. Net::FTP simply
1660
+ records this value and uses it when during the next data transfer. For this
1661
+ reason this method will not return an error, but setting it may cause
1662
+ a subsequent data transfer to fail.
1663
+
1664
+ =item C<rmdir($dir[, $recurse])>
1665
+
1666
+ Remove the directory with the name C<$dir>. If C<$recurse> is I<true> then
1667
+ C<rmdir> will attempt to delete everything inside the directory.
1668
+
1669
+ =item C<mkdir($dir[, $recurse])>
1670
+
1671
+ Create a new directory with the name C<$dir>. If C<$recurse> is I<true> then
1672
+ C<mkdir> will attempt to create all the directories in the given path.
1673
+
1674
+ Returns the full pathname to the new directory.
1675
+
1676
+ =item C<alloc($size[, $record_size])>
1677
+
1678
+ The alloc command allows you to give the ftp server a hint about the size
1679
+ of the file about to be transferred using the ALLO ftp command. Some storage
1680
+ systems use this to make intelligent decisions about how to store the file.
1681
+ The C<$size> argument represents the size of the file in bytes. The
1682
+ C<$record_size> argument indicates a maximum record or page size for files
1683
+ sent with a record or page structure.
1684
+
1685
+ The size of the file will be determined, and sent to the server
1686
+ automatically for normal files so that this method need only be called if
1687
+ you are transferring data from a socket, named pipe, or other stream not
1688
+ associated with a normal file.
1689
+
1690
+ =item C<ls([$dir])>
1691
+
1692
+ Get a directory listing of C<$dir>, or the current directory.
1693
+
1694
+ In an array context, returns a list of lines returned from the server. In
1695
+ a scalar context, returns a reference to a list.
1696
+
1697
+ =item C<dir([$dir])>
1698
+
1699
+ Get a directory listing of C<$dir>, or the current directory in long format.
1700
+
1701
+ In an array context, returns a list of lines returned from the server. In
1702
+ a scalar context, returns a reference to a list.
1703
+
1704
+ =item C<get($remote_file[, $local_file[, $where]])>
1705
+
1706
+ Get C<$remote_file> from the server and store locally. C<$local_file> may be
1707
+ a filename or a filehandle. If not specified, the file will be stored in
1708
+ the current directory with the same leafname as the remote file.
1709
+
1710
+ If C<$where> is given then the first C<$where> bytes of the file will
1711
+ not be transferred, and the remaining bytes will be appended to
1712
+ the local file if it already exists.
1713
+
1714
+ Returns C<$local_file>, or the generated local file name if C<$local_file>
1715
+ is not given. If an error was encountered undef is returned.
1716
+
1717
+ =item C<put($local_file[, $remote_file])>
1718
+
1719
+ Put a file on the remote server. C<$local_file> may be a name or a filehandle.
1720
+ If C<$local_file> is a filehandle then C<$remote_file> must be specified. If
1721
+ C<$remote_file> is not specified then the file will be stored in the current
1722
+ directory with the same leafname as C<$local_file>.
1723
+
1724
+ Returns C<$remote_file>, or the generated remote filename if C<$remote_file>
1725
+ is not given.
1726
+
1727
+ B<NOTE>: If for some reason the transfer does not complete and an error is
1728
+ returned then the contents that had been transferred will not be remove
1729
+ automatically.
1730
+
1731
+ =item C<put_unique($local_file[, $remote_file])>
1732
+
1733
+ Same as put but uses the C<STOU> command.
1734
+
1735
+ Returns the name of the file on the server.
1736
+
1737
+ =item C<append($local_file[, $remote_file])>
1738
+
1739
+ Same as put but appends to the file on the remote server.
1740
+
1741
+ Returns C<$remote_file>, or the generated remote filename if C<$remote_file>
1742
+ is not given.
1743
+
1744
+ =item C<unique_name()>
1745
+
1746
+ Returns the name of the last file stored on the server using the
1747
+ C<STOU> command.
1748
+
1749
+ =item C<mdtm($file)>
1750
+
1751
+ Returns the I<modification time> of the given file
1752
+
1753
+ =item C<size($file)>
1754
+
1755
+ Returns the size in bytes for the given file as stored on the remote server.
1756
+
1757
+ B<NOTE>: The size reported is the size of the stored file on the remote server.
1758
+ If the file is subsequently transferred from the server in ASCII mode
1759
+ and the remote server and local machine have different ideas about
1760
+ "End Of Line" then the size of file on the local machine after transfer
1761
+ may be different.
1762
+
1763
+ =item C<supported($cmd)>
1764
+
1765
+ Returns TRUE if the remote server supports the given command.
1766
+
1767
+ =item C<hash([$filehandle_glob_ref[, $bytes_per_hash_mark]])>
1768
+
1769
+ Called without parameters, or with the first argument false, hash marks
1770
+ are suppressed. If the first argument is true but not a reference to a
1771
+ file handle glob, then \*STDERR is used. The second argument is the number
1772
+ of bytes per hash mark printed, and defaults to 1024. In all cases the
1773
+ return value is a reference to an array of two: the filehandle glob reference
1774
+ and the bytes per hash mark.
1775
+
1776
+ =item C<feature($name)>
1777
+
1778
+ Determine if the server supports the specified feature. The return
1779
+ value is a list of lines the server responded with to describe the
1780
+ options that it supports for the given feature. If the feature is
1781
+ unsupported then the empty list is returned.
1782
+
1783
+ if ($ftp->feature( 'MDTM' )) {
1784
+ # Do something
1785
+ }
1786
+
1787
+ if (grep { /\bTLS\b/ } $ftp->feature('AUTH')) {
1788
+ # Server supports TLS
1789
+ }
1790
+
1791
+ =back
1792
+
1793
+ The following methods can return different results depending on
1794
+ how they are called. If the user explicitly calls either
1795
+ of the C<pasv> or C<port> methods then these methods will
1796
+ return a I<true> or I<false> value. If the user does not
1797
+ call either of these methods then the result will be a
1798
+ reference to a C<Net::FTP::dataconn> based object.
1799
+
1800
+ =over 4
1801
+
1802
+ =item C<nlst([$dir])>
1803
+
1804
+ Send an C<NLST> command to the server, with an optional parameter.
1805
+
1806
+ =item C<list([$dir])>
1807
+
1808
+ Same as C<nlst> but using the C<LIST> command
1809
+
1810
+ =item C<retr($file)>
1811
+
1812
+ Begin the retrieval of a file called C<$file> from the remote server.
1813
+
1814
+ =item C<stor($file)>
1815
+
1816
+ Tell the server that you wish to store a file. C<$file> is the
1817
+ name of the new file that should be created.
1818
+
1819
+ =item C<stou($file)>
1820
+
1821
+ Same as C<stor> but using the C<STOU> command. The name of the unique
1822
+ file which was created on the server will be available via the C<unique_name>
1823
+ method after the data connection has been closed.
1824
+
1825
+ =item C<appe($file)>
1826
+
1827
+ Tell the server that we want to append some data to the end of a file
1828
+ called C<$file>. If this file does not exist then create it.
1829
+
1830
+ =back
1831
+
1832
+ If for some reason you want to have complete control over the data connection,
1833
+ this includes generating it and calling the C<response> method when required,
1834
+ then the user can use these methods to do so.
1835
+
1836
+ However calling these methods only affects the use of the methods above that
1837
+ can return a data connection. They have no effect on methods C<get>, C<put>,
1838
+ C<put_unique> and those that do not require data connections.
1839
+
1840
+ =over 4
1841
+
1842
+ =item C<port([$port])>
1843
+
1844
+ =item C<eprt([$port])>
1845
+
1846
+ Send a C<PORT> (IPv4) or C<EPRT> (IPv6) command to the server. If C<$port> is
1847
+ specified then it is sent to the server. If not, then a listen socket is created
1848
+ and the correct information sent to the server.
1849
+
1850
+ =item C<pasv()>
1851
+
1852
+ =item C<epsv()>
1853
+
1854
+ Tell the server to go into passive mode (C<pasv> for IPv4, C<epsv> for IPv6).
1855
+ Returns the text that represents the port on which the server is listening, this
1856
+ text is in a suitable form to send to another ftp server using the C<port> or
1857
+ C<eprt> method.
1858
+
1859
+ =back
1860
+
1861
+ The following methods can be used to transfer files between two remote
1862
+ servers, providing that these two servers can connect directly to each other.
1863
+
1864
+ =over 4
1865
+
1866
+ =item C<pasv_xfer($src_file, $dest_server[, $dest_file ])>
1867
+
1868
+ This method will do a file transfer between two remote ftp servers. If
1869
+ C<$dest_file> is omitted then the leaf name of C<$src_file> will be used.
1870
+
1871
+ =item C<pasv_xfer_unique($src_file, $dest_server[, $dest_file ])>
1872
+
1873
+ Like C<pasv_xfer> but the file is stored on the remote server using
1874
+ the STOU command.
1875
+
1876
+ =item C<pasv_wait($non_pasv_server)>
1877
+
1878
+ This method can be used to wait for a transfer to complete between a passive
1879
+ server and a non-passive server. The method should be called on the passive
1880
+ server with the C<Net::FTP> object for the non-passive server passed as an
1881
+ argument.
1882
+
1883
+ =item C<abort()>
1884
+
1885
+ Abort the current data transfer.
1886
+
1887
+ =item C<quit()>
1888
+
1889
+ Send the QUIT command to the remote FTP server and close the socket connection.
1890
+
1891
+ =back
1892
+
1893
+ =head2 Methods for the Adventurous
1894
+
1895
+ =over 4
1896
+
1897
+ =item C<quot($cmd[, $args])>
1898
+
1899
+ Send a command, that Net::FTP does not directly support, to the remote
1900
+ server and wait for a response.
1901
+
1902
+ Returns most significant digit of the response code.
1903
+
1904
+ B<WARNING> This call should only be used on commands that do not require
1905
+ data connections. Misuse of this method can hang the connection.
1906
+
1907
+ =item C<can_inet6()>
1908
+
1909
+ Returns whether we can use IPv6.
1910
+
1911
+ =item C<can_ssl()>
1912
+
1913
+ Returns whether we can use SSL.
1914
+
1915
+ =back
1916
+
1917
+ =head2 The dataconn Class
1918
+
1919
+ Some of the methods defined in C<Net::FTP> return an object which will
1920
+ be derived from the C<Net::FTP::dataconn> class. See L<Net::FTP::dataconn> for
1921
+ more details.
1922
+
1923
+ =head2 Unimplemented
1924
+
1925
+ The following RFC959 commands have not been implemented:
1926
+
1927
+ =over 4
1928
+
1929
+ =item C<SMNT>
1930
+
1931
+ Mount a different file system structure without changing login or
1932
+ accounting information.
1933
+
1934
+ =item C<HELP>
1935
+
1936
+ Ask the server for "helpful information" (that's what the RFC says) on
1937
+ the commands it accepts.
1938
+
1939
+ =item C<MODE>
1940
+
1941
+ Specifies transfer mode (stream, block or compressed) for file to be
1942
+ transferred.
1943
+
1944
+ =item C<SYST>
1945
+
1946
+ Request remote server system identification.
1947
+
1948
+ =item C<STAT>
1949
+
1950
+ Request remote server status.
1951
+
1952
+ =item C<STRU>
1953
+
1954
+ Specifies file structure for file to be transferred.
1955
+
1956
+ =item C<REIN>
1957
+
1958
+ Reinitialize the connection, flushing all I/O and account information.
1959
+
1960
+ =back
1961
+
1962
+ =head1 EXPORTS
1963
+
1964
+ I<None>.
1965
+
1966
+ =head1 KNOWN BUGS
1967
+
1968
+ See L<https://rt.cpan.org/Dist/Display.html?Status=Active&Queue=libnet>.
1969
+
1970
+ =head2 Reporting Bugs
1971
+
1972
+ When reporting bugs/problems please include as much information as possible.
1973
+ It may be difficult for me to reproduce the problem as almost every setup
1974
+ is different.
1975
+
1976
+ A small script which yields the problem will probably be of help. It would
1977
+ also be useful if this script was run with the extra options C<< Debug => 1 >>
1978
+ passed to the constructor, and the output sent with the bug report. If you
1979
+ cannot include a small script then please include a Debug trace from a
1980
+ run of your program which does yield the problem.
1981
+
1982
+ =head1 SEE ALSO
1983
+
1984
+ L<Net::Netrc>,
1985
+ L<Net::Cmd>,
1986
+ L<IO::Socket::SSL>;
1987
+
1988
+ L<ftp(1)>,
1989
+ L<ftpd(8)>;
1990
+
1991
+ L<https://www.ietf.org/rfc/rfc959.txt>,
1992
+ L<https://www.ietf.org/rfc/rfc2428.txt>,
1993
+ L<https://www.ietf.org/rfc/rfc4217.txt>.
1994
+
1995
+ =head1 ACKNOWLEDGEMENTS
1996
+
1997
+ Henry Gabryjelski E<lt>L<henryg@WPI.EDU|mailto:henryg@WPI.EDU>E<gt> - for the
1998
+ suggestion of creating directories recursively.
1999
+
2000
+ Nathan Torkington E<lt>L<gnat@frii.com|mailto:gnat@frii.com>E<gt> - for some
2001
+ input on the documentation.
2002
+
2003
+ Roderick Schertler E<lt>L<roderick@gate.net|mailto:roderick@gate.net>E<gt> - for
2004
+ various inputs
2005
+
2006
+ =head1 AUTHOR
2007
+
2008
+ Graham Barr E<lt>L<gbarr@pobox.com|mailto:gbarr@pobox.com>E<gt>.
2009
+
2010
+ Steve Hay E<lt>L<shay@cpan.org|mailto:shay@cpan.org>E<gt> is now maintaining
2011
+ libnet as of version 1.22_02.
2012
+
2013
+ =head1 COPYRIGHT
2014
+
2015
+ Copyright (C) 1995-2004 Graham Barr. All rights reserved.
2016
+
2017
+ Copyright (C) 2013-2017, 2020, 2022 Steve Hay. All rights reserved.
2018
+
2019
+ =head1 LICENCE
2020
+
2021
+ This module is free software; you can redistribute it and/or modify it under the
2022
+ same terms as Perl itself, i.e. under the terms of either the GNU General Public
2023
+ License or the Artistic License, as specified in the F<LICENCE> file.
2024
+
2025
+ =head1 VERSION
2026
+
2027
+ Version 3.15
2028
+
2029
+ =head1 DATE
2030
+
2031
+ 20 March 2023
2032
+
2033
+ =head1 HISTORY
2034
+
2035
+ See the F<Changes> file.
2036
+
2037
+ =cut
git/usr/share/perl5/core_perl/Net/NNTP.pm ADDED
@@ -0,0 +1,1321 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Net::NNTP.pm
2
+ #
3
+ # Copyright (C) 1995-1997 Graham Barr. All rights reserved.
4
+ # Copyright (C) 2013-2016, 2020 Steve Hay. All rights reserved.
5
+ # This module is free software; you can redistribute it and/or modify it under
6
+ # the same terms as Perl itself, i.e. under the terms of either the GNU General
7
+ # Public License or the Artistic License, as specified in the F<LICENCE> file.
8
+
9
+ package Net::NNTP;
10
+
11
+ use 5.008001;
12
+
13
+ use strict;
14
+ use warnings;
15
+
16
+ use Carp;
17
+ use IO::Socket;
18
+ use Net::Cmd;
19
+ use Net::Config;
20
+ use Time::Local;
21
+
22
+ our $VERSION = "3.15";
23
+
24
+ # Code for detecting if we can use SSL
25
+ my $ssl_class = eval {
26
+ require IO::Socket::SSL;
27
+ # first version with default CA on most platforms
28
+ no warnings 'numeric';
29
+ IO::Socket::SSL->VERSION(2.007);
30
+ } && 'IO::Socket::SSL';
31
+
32
+ my $nossl_warn = !$ssl_class &&
33
+ 'To use SSL please install IO::Socket::SSL with version>=2.007';
34
+
35
+ # Code for detecting if we can use IPv6
36
+ my $family_key = 'Domain';
37
+ my $inet6_class = eval {
38
+ require IO::Socket::IP;
39
+ no warnings 'numeric';
40
+ IO::Socket::IP->VERSION(0.25) || die;
41
+ $family_key = 'Family';
42
+ } && 'IO::Socket::IP' || eval {
43
+ require IO::Socket::INET6;
44
+ no warnings 'numeric';
45
+ IO::Socket::INET6->VERSION(2.62);
46
+ } && 'IO::Socket::INET6';
47
+
48
+
49
+ sub can_ssl { $ssl_class };
50
+ sub can_inet6 { $inet6_class };
51
+
52
+ our @ISA = ('Net::Cmd', $inet6_class || 'IO::Socket::INET');
53
+
54
+
55
+ sub new {
56
+ my $self = shift;
57
+ my $type = ref($self) || $self;
58
+ my ($host, %arg);
59
+ if (@_ % 2) {
60
+ $host = shift;
61
+ %arg = @_;
62
+ }
63
+ else {
64
+ %arg = @_;
65
+ $host = delete $arg{Host};
66
+ }
67
+ my $obj;
68
+
69
+ $host ||= $ENV{NNTPSERVER} || $ENV{NEWSHOST};
70
+
71
+ my $hosts = defined $host ? [$host] : $NetConfig{nntp_hosts};
72
+
73
+ @{$hosts} = qw(news)
74
+ unless @{$hosts};
75
+
76
+ my %connect = ( Proto => 'tcp');
77
+
78
+ if ($arg{SSL}) {
79
+ # SSL from start
80
+ die $nossl_warn if ! $ssl_class;
81
+ $arg{Port} ||= 563;
82
+ $connect{$_} = $arg{$_} for(grep { m{^SSL_} } keys %arg);
83
+ }
84
+
85
+ foreach my $o (qw(LocalAddr LocalPort Timeout)) {
86
+ $connect{$o} = $arg{$o} if exists $arg{$o};
87
+ }
88
+ $connect{$family_key} = $arg{Domain} || $arg{Family};
89
+ $connect{Timeout} = 120 unless defined $connect{Timeout};
90
+ $connect{PeerPort} = $arg{Port} || 'nntp(119)';
91
+ foreach my $h (@{$hosts}) {
92
+ $connect{PeerAddr} = $h;
93
+ $obj = $type->SUPER::new(%connect) or next;
94
+ ${*$obj}{'net_nntp_host'} = $h;
95
+ ${*$obj}{'net_nntp_arg'} = \%arg;
96
+ if ($arg{SSL}) {
97
+ Net::NNTP::_SSL->start_SSL($obj,%arg) or next;
98
+ }
99
+ }
100
+
101
+ return
102
+ unless defined $obj;
103
+
104
+ $obj->autoflush(1);
105
+ $obj->debug(exists $arg{Debug} ? $arg{Debug} : undef);
106
+
107
+ unless ($obj->response() == CMD_OK) {
108
+ $obj->close;
109
+ return;
110
+ }
111
+
112
+ my $c = $obj->code;
113
+ my @m = $obj->message;
114
+
115
+ unless (exists $arg{Reader} && $arg{Reader} == 0) {
116
+
117
+ # if server is INN and we have transfer rights the we are currently
118
+ # talking to innd not nnrpd
119
+ if ($obj->reader) {
120
+
121
+ # If reader succeeds the we need to consider this code to determine postok
122
+ $c = $obj->code;
123
+ }
124
+ else {
125
+
126
+ # I want to ignore this failure, so restore the previous status.
127
+ $obj->set_status($c, \@m);
128
+ }
129
+ }
130
+
131
+ ${*$obj}{'net_nntp_post'} = $c == 200 ? 1 : 0;
132
+
133
+ $obj;
134
+ }
135
+
136
+
137
+ sub host {
138
+ my $me = shift;
139
+ ${*$me}{'net_nntp_host'};
140
+ }
141
+
142
+
143
+ sub debug_text {
144
+ my $nntp = shift;
145
+ my $inout = shift;
146
+ my $text = shift;
147
+
148
+ if ( (ref($nntp) and $nntp->code == 350 and $text =~ /^(\S+)/)
149
+ || ($text =~ /^(authinfo\s+pass)/io))
150
+ {
151
+ $text = "$1 ....\n";
152
+ }
153
+
154
+ $text;
155
+ }
156
+
157
+
158
+ sub postok {
159
+ @_ == 1 or croak 'usage: $nntp->postok()';
160
+ my $nntp = shift;
161
+ ${*$nntp}{'net_nntp_post'} || 0;
162
+ }
163
+
164
+
165
+ sub starttls {
166
+ my $self = shift;
167
+ $ssl_class or die $nossl_warn;
168
+ $self->_STARTTLS or return;
169
+ Net::NNTP::_SSL->start_SSL($self,
170
+ %{ ${*$self}{'net_nntp_arg'} }, # (ssl) args given in new
171
+ @_ # more (ssl) args
172
+ ) or return;
173
+ return 1;
174
+ }
175
+
176
+
177
+ sub article {
178
+ @_ >= 1 && @_ <= 3 or croak 'usage: $nntp->article([{$msgid|$msgnum}[, $fh]])';
179
+ my $nntp = shift;
180
+ my @fh;
181
+
182
+ @fh = (pop) if @_ == 2 || (@_ && (ref($_[0]) || ref(\$_[0]) eq 'GLOB'));
183
+
184
+ $nntp->_ARTICLE(@_)
185
+ ? $nntp->read_until_dot(@fh)
186
+ : undef;
187
+ }
188
+
189
+
190
+ sub articlefh {
191
+ @_ >= 1 && @_ <= 2 or croak 'usage: $nntp->articlefh([{$msgid|$msgnum}])';
192
+ my $nntp = shift;
193
+
194
+ return unless $nntp->_ARTICLE(@_);
195
+ return $nntp->tied_fh;
196
+ }
197
+
198
+
199
+ sub authinfo {
200
+ @_ == 3 or croak 'usage: $nntp->authinfo($user, $pass)';
201
+ my ($nntp, $user, $pass) = @_;
202
+
203
+ $nntp->_AUTHINFO("USER", $user) == CMD_MORE
204
+ && $nntp->_AUTHINFO("PASS", $pass) == CMD_OK;
205
+ }
206
+
207
+
208
+ sub authinfo_simple {
209
+ @_ == 3 or croak 'usage: $nntp->authinfo_simple($user, $pass)';
210
+ my ($nntp, $user, $pass) = @_;
211
+
212
+ $nntp->_AUTHINFO('SIMPLE') == CMD_MORE
213
+ && $nntp->command($user, $pass)->response == CMD_OK;
214
+ }
215
+
216
+
217
+ sub body {
218
+ @_ >= 1 && @_ <= 3 or croak 'usage: $nntp->body([{$msgid|$msgnum}[, $fh]])';
219
+ my $nntp = shift;
220
+ my @fh;
221
+
222
+ @fh = (pop) if @_ == 2 || (@_ && ref($_[0]) || ref(\$_[0]) eq 'GLOB');
223
+
224
+ $nntp->_BODY(@_)
225
+ ? $nntp->read_until_dot(@fh)
226
+ : undef;
227
+ }
228
+
229
+
230
+ sub bodyfh {
231
+ @_ >= 1 && @_ <= 2 or croak 'usage: $nntp->bodyfh([{$msgid|$msgnum}])';
232
+ my $nntp = shift;
233
+ return unless $nntp->_BODY(@_);
234
+ return $nntp->tied_fh;
235
+ }
236
+
237
+
238
+ sub head {
239
+ @_ >= 1 && @_ <= 3 or croak 'usage: $nntp->head([{$msgid|$msgnum}[, $fh]])';
240
+ my $nntp = shift;
241
+ my @fh;
242
+
243
+ @fh = (pop) if @_ == 2 || (@_ && ref($_[0]) || ref(\$_[0]) eq 'GLOB');
244
+
245
+ $nntp->_HEAD(@_)
246
+ ? $nntp->read_until_dot(@fh)
247
+ : undef;
248
+ }
249
+
250
+
251
+ sub headfh {
252
+ @_ >= 1 && @_ <= 2 or croak 'usage: $nntp->headfh([{$msgid|$msgnum}])';
253
+ my $nntp = shift;
254
+ return unless $nntp->_HEAD(@_);
255
+ return $nntp->tied_fh;
256
+ }
257
+
258
+
259
+ sub nntpstat {
260
+ @_ == 1 || @_ == 2 or croak 'usage: $nntp->nntpstat([{$msgid|$msgnum}])';
261
+ my $nntp = shift;
262
+
263
+ $nntp->_STAT(@_) && $nntp->message =~ /(<[^>]+>)/o
264
+ ? $1
265
+ : undef;
266
+ }
267
+
268
+
269
+ sub group {
270
+ @_ == 1 || @_ == 2 or croak 'usage: $nntp->group([$group])';
271
+ my $nntp = shift;
272
+ my $grp = ${*$nntp}{'net_nntp_group'};
273
+
274
+ return $grp
275
+ unless (@_ || wantarray);
276
+
277
+ my $newgrp = shift;
278
+
279
+ $newgrp = (defined($grp) and length($grp)) ? $grp : ""
280
+ unless defined($newgrp) and length($newgrp);
281
+
282
+ return
283
+ unless $nntp->_GROUP($newgrp) and $nntp->message =~ /(\d+)\s+(\d+)\s+(\d+)\s+(\S+)/;
284
+
285
+ my ($count, $first, $last, $group) = ($1, $2, $3, $4);
286
+
287
+ # group may be replied as '(current group)'
288
+ $group = ${*$nntp}{'net_nntp_group'}
289
+ if $group =~ /\(/;
290
+
291
+ ${*$nntp}{'net_nntp_group'} = $group;
292
+
293
+ wantarray
294
+ ? ($count, $first, $last, $group)
295
+ : $group;
296
+ }
297
+
298
+
299
+ sub help {
300
+ @_ == 1 or croak 'usage: $nntp->help()';
301
+ my $nntp = shift;
302
+
303
+ $nntp->_HELP
304
+ ? $nntp->read_until_dot
305
+ : undef;
306
+ }
307
+
308
+
309
+ sub ihave {
310
+ @_ >= 2 or croak 'usage: $nntp->ihave($msgid[, $message])';
311
+ my $nntp = shift;
312
+ my $msgid = shift;
313
+
314
+ $nntp->_IHAVE($msgid) && $nntp->datasend(@_)
315
+ ? @_ == 0 || $nntp->dataend
316
+ : undef;
317
+ }
318
+
319
+
320
+ sub last {
321
+ @_ == 1 or croak 'usage: $nntp->last()';
322
+ my $nntp = shift;
323
+
324
+ $nntp->_LAST && $nntp->message =~ /(<[^>]+>)/o
325
+ ? $1
326
+ : undef;
327
+ }
328
+
329
+
330
+ sub list {
331
+ @_ == 1 or croak 'usage: $nntp->list()';
332
+ my $nntp = shift;
333
+
334
+ $nntp->_LIST
335
+ ? $nntp->_grouplist
336
+ : undef;
337
+ }
338
+
339
+
340
+ sub newgroups {
341
+ @_ >= 2 or croak 'usage: $nntp->newgroups($since[, $distributions])';
342
+ my $nntp = shift;
343
+ my $since = _timestr(shift);
344
+ my $distributions = shift || "";
345
+
346
+ $distributions = join(",", @{$distributions})
347
+ if ref($distributions);
348
+
349
+ $nntp->_NEWGROUPS($since, $distributions)
350
+ ? $nntp->_grouplist
351
+ : undef;
352
+ }
353
+
354
+
355
+ sub newnews {
356
+ @_ >= 2 && @_ <= 4
357
+ or croak 'usage: $nntp->newnews($since[, $groups[, $distributions]])';
358
+ my $nntp = shift;
359
+ my $since = _timestr(shift);
360
+ my $groups = @_ ? shift : $nntp->group;
361
+ my $distributions = shift || "";
362
+
363
+ $groups ||= "*";
364
+ $groups = join(",", @{$groups})
365
+ if ref($groups);
366
+
367
+ $distributions = join(",", @{$distributions})
368
+ if ref($distributions);
369
+
370
+ $nntp->_NEWNEWS($groups, $since, $distributions)
371
+ ? $nntp->_articlelist
372
+ : undef;
373
+ }
374
+
375
+
376
+ sub next {
377
+ @_ == 1 or croak 'usage: $nntp->next()';
378
+ my $nntp = shift;
379
+
380
+ $nntp->_NEXT && $nntp->message =~ /(<[^>]+>)/o
381
+ ? $1
382
+ : undef;
383
+ }
384
+
385
+
386
+ sub post {
387
+ @_ >= 1 or croak 'usage: $nntp->post([$message])';
388
+ my $nntp = shift;
389
+
390
+ $nntp->_POST() && $nntp->datasend(@_)
391
+ ? @_ == 0 || $nntp->dataend
392
+ : undef;
393
+ }
394
+
395
+
396
+ sub postfh {
397
+ my $nntp = shift;
398
+ return unless $nntp->_POST();
399
+ return $nntp->tied_fh;
400
+ }
401
+
402
+
403
+ sub quit {
404
+ @_ == 1 or croak 'usage: $nntp->quit()';
405
+ my $nntp = shift;
406
+
407
+ $nntp->_QUIT;
408
+ $nntp->close;
409
+ }
410
+
411
+
412
+ sub slave {
413
+ @_ == 1 or croak 'usage: $nntp->slave()';
414
+ my $nntp = shift;
415
+
416
+ $nntp->_SLAVE;
417
+ }
418
+
419
+ ##
420
+ ## The following methods are not implemented by all servers
421
+ ##
422
+
423
+
424
+ sub active {
425
+ @_ == 1 || @_ == 2 or croak 'usage: $nntp->active([$pattern])';
426
+ my $nntp = shift;
427
+
428
+ $nntp->_LIST('ACTIVE', @_)
429
+ ? $nntp->_grouplist
430
+ : undef;
431
+ }
432
+
433
+
434
+ sub active_times {
435
+ @_ == 1 or croak 'usage: $nntp->active_times()';
436
+ my $nntp = shift;
437
+
438
+ $nntp->_LIST('ACTIVE.TIMES')
439
+ ? $nntp->_grouplist
440
+ : undef;
441
+ }
442
+
443
+
444
+ sub distributions {
445
+ @_ == 1 or croak 'usage: $nntp->distributions()';
446
+ my $nntp = shift;
447
+
448
+ $nntp->_LIST('DISTRIBUTIONS')
449
+ ? $nntp->_description
450
+ : undef;
451
+ }
452
+
453
+
454
+ sub distribution_patterns {
455
+ @_ == 1 or croak 'usage: $nntp->distribution_patterns()';
456
+ my $nntp = shift;
457
+
458
+ my $arr;
459
+ local $_;
460
+
461
+ ## no critic (ControlStructures::ProhibitMutatingListFunctions)
462
+ $nntp->_LIST('DISTRIB.PATS')
463
+ && ($arr = $nntp->read_until_dot)
464
+ ? [grep { /^\d/ && (chomp, $_ = [split /:/]) } @$arr]
465
+ : undef;
466
+ }
467
+
468
+
469
+ sub newsgroups {
470
+ @_ == 1 || @_ == 2 or croak 'usage: $nntp->newsgroups([$pattern])';
471
+ my $nntp = shift;
472
+
473
+ $nntp->_LIST('NEWSGROUPS', @_)
474
+ ? $nntp->_description
475
+ : undef;
476
+ }
477
+
478
+
479
+ sub overview_fmt {
480
+ @_ == 1 or croak 'usage: $nntp->overview_fmt()';
481
+ my $nntp = shift;
482
+
483
+ $nntp->_LIST('OVERVIEW.FMT')
484
+ ? $nntp->_articlelist
485
+ : undef;
486
+ }
487
+
488
+
489
+ sub subscriptions {
490
+ @_ == 1 or croak 'usage: $nntp->subscriptions()';
491
+ my $nntp = shift;
492
+
493
+ $nntp->_LIST('SUBSCRIPTIONS')
494
+ ? $nntp->_articlelist
495
+ : undef;
496
+ }
497
+
498
+
499
+ sub listgroup {
500
+ @_ == 1 || @_ == 2 or croak 'usage: $nntp->listgroup([$group])';
501
+ my $nntp = shift;
502
+
503
+ $nntp->_LISTGROUP(@_)
504
+ ? $nntp->_articlelist
505
+ : undef;
506
+ }
507
+
508
+
509
+ sub reader {
510
+ @_ == 1 or croak 'usage: $nntp->reader()';
511
+ my $nntp = shift;
512
+
513
+ $nntp->_MODE('READER');
514
+ }
515
+
516
+
517
+ sub xgtitle {
518
+ @_ == 1 || @_ == 2 or croak 'usage: $nntp->xgtitle([$pattern])';
519
+ my $nntp = shift;
520
+
521
+ $nntp->_XGTITLE(@_)
522
+ ? $nntp->_description
523
+ : undef;
524
+ }
525
+
526
+
527
+ sub xhdr {
528
+ @_ >= 2 && @_ <= 4 or croak 'usage: $nntp->xhdr($header[, $message_spec])';
529
+ my $nntp = shift;
530
+ my $header = shift;
531
+ my $arg = _msg_arg(@_);
532
+
533
+ $nntp->_XHDR($header, $arg)
534
+ ? $nntp->_description
535
+ : undef;
536
+ }
537
+
538
+
539
+ sub xover {
540
+ @_ == 2 || @_ == 3 or croak 'usage: $nntp->xover($message_spec)';
541
+ my $nntp = shift;
542
+ my $arg = _msg_arg(@_);
543
+
544
+ $nntp->_XOVER($arg)
545
+ ? $nntp->_fieldlist
546
+ : undef;
547
+ }
548
+
549
+
550
+ sub xpat {
551
+ @_ == 4 || @_ == 5 or croak 'usage: $nntp->xpat($header, $pattern, $message_spec )';
552
+ my $nntp = shift;
553
+ my $header = shift;
554
+ my $pattern = shift;
555
+ my $arg = _msg_arg(@_);
556
+
557
+ $pattern = join(" ", @$pattern)
558
+ if ref($pattern);
559
+
560
+ $nntp->_XPAT($header, $arg, $pattern)
561
+ ? $nntp->_description
562
+ : undef;
563
+ }
564
+
565
+
566
+ sub xpath {
567
+ @_ == 2 or croak 'usage: $nntp->xpath($message_id)';
568
+ my ($nntp, $message_id) = @_;
569
+
570
+ return
571
+ unless $nntp->_XPATH($message_id);
572
+
573
+ my $m;
574
+ ($m = $nntp->message) =~ s/^\d+\s+//o;
575
+ my @p = split /\s+/, $m;
576
+
577
+ wantarray ? @p : $p[0];
578
+ }
579
+
580
+
581
+ sub xrover {
582
+ @_ == 2 || @_ == 3 or croak 'usage: $nntp->xrover($message_spec)';
583
+ my $nntp = shift;
584
+ my $arg = _msg_arg(@_);
585
+
586
+ $nntp->_XROVER($arg)
587
+ ? $nntp->_description
588
+ : undef;
589
+ }
590
+
591
+
592
+ sub date {
593
+ @_ == 1 or croak 'usage: $nntp->date()';
594
+ my $nntp = shift;
595
+
596
+ $nntp->_DATE
597
+ && $nntp->message =~ /(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)/
598
+ ? timegm($6, $5, $4, $3, $2 - 1, $1)
599
+ : undef;
600
+ }
601
+
602
+
603
+ ##
604
+ ## Private subroutines
605
+ ##
606
+
607
+
608
+ sub _msg_arg {
609
+ my $spec = shift;
610
+ my $arg = "";
611
+
612
+ if (@_) {
613
+ carp "Depriciated passing of two message numbers, " . "pass a reference"
614
+ if $^W;
615
+ $spec = [$spec, $_[0]];
616
+ }
617
+
618
+ if (defined $spec) {
619
+ if (ref($spec)) {
620
+ $arg = $spec->[0];
621
+ if (defined $spec->[1]) {
622
+ $arg .= "-"
623
+ if $spec->[1] != $spec->[0];
624
+ $arg .= $spec->[1]
625
+ if $spec->[1] > $spec->[0];
626
+ }
627
+ }
628
+ else {
629
+ $arg = $spec;
630
+ }
631
+ }
632
+
633
+ $arg;
634
+ }
635
+
636
+
637
+ sub _timestr {
638
+ my $time = shift;
639
+ my @g = reverse((gmtime($time))[0 .. 5]);
640
+ $g[1] += 1;
641
+ $g[0] %= 100;
642
+ sprintf "%02d%02d%02d %02d%02d%02d GMT", @g;
643
+ }
644
+
645
+
646
+ sub _grouplist {
647
+ my $nntp = shift;
648
+ my $arr = $nntp->read_until_dot
649
+ or return;
650
+
651
+ my $hash = {};
652
+
653
+ foreach my $ln (@$arr) {
654
+ my @a = split(/[\s\n]+/, $ln);
655
+ $hash->{$a[0]} = [@a[1, 2, 3]];
656
+ }
657
+
658
+ $hash;
659
+ }
660
+
661
+
662
+ sub _fieldlist {
663
+ my $nntp = shift;
664
+ my $arr = $nntp->read_until_dot
665
+ or return;
666
+
667
+ my $hash = {};
668
+
669
+ foreach my $ln (@$arr) {
670
+ my @a = split(/[\t\n]/, $ln);
671
+ my $m = shift @a;
672
+ $hash->{$m} = [@a];
673
+ }
674
+
675
+ $hash;
676
+ }
677
+
678
+
679
+ sub _articlelist {
680
+ my $nntp = shift;
681
+ my $arr = $nntp->read_until_dot;
682
+
683
+ chomp(@$arr)
684
+ if $arr;
685
+
686
+ $arr;
687
+ }
688
+
689
+
690
+ sub _description {
691
+ my $nntp = shift;
692
+ my $arr = $nntp->read_until_dot
693
+ or return;
694
+
695
+ my $hash = {};
696
+
697
+ foreach my $ln (@$arr) {
698
+ chomp($ln);
699
+
700
+ $hash->{$1} = $ln
701
+ if $ln =~ s/^\s*(\S+)\s*//o;
702
+ }
703
+
704
+ $hash;
705
+
706
+ }
707
+
708
+ ##
709
+ ## The commands
710
+ ##
711
+
712
+
713
+ sub _ARTICLE { shift->command('ARTICLE', @_)->response == CMD_OK }
714
+ sub _AUTHINFO { shift->command('AUTHINFO', @_)->response }
715
+ sub _BODY { shift->command('BODY', @_)->response == CMD_OK }
716
+ sub _DATE { shift->command('DATE')->response == CMD_INFO }
717
+ sub _GROUP { shift->command('GROUP', @_)->response == CMD_OK }
718
+ sub _HEAD { shift->command('HEAD', @_)->response == CMD_OK }
719
+ sub _HELP { shift->command('HELP', @_)->response == CMD_INFO }
720
+ sub _IHAVE { shift->command('IHAVE', @_)->response == CMD_MORE }
721
+ sub _LAST { shift->command('LAST')->response == CMD_OK }
722
+ sub _LIST { shift->command('LIST', @_)->response == CMD_OK }
723
+ sub _LISTGROUP { shift->command('LISTGROUP', @_)->response == CMD_OK }
724
+ sub _NEWGROUPS { shift->command('NEWGROUPS', @_)->response == CMD_OK }
725
+ sub _NEWNEWS { shift->command('NEWNEWS', @_)->response == CMD_OK }
726
+ sub _NEXT { shift->command('NEXT')->response == CMD_OK }
727
+ sub _POST { shift->command('POST', @_)->response == CMD_MORE }
728
+ sub _QUIT { shift->command('QUIT', @_)->response == CMD_OK }
729
+ sub _SLAVE { shift->command('SLAVE', @_)->response == CMD_OK }
730
+ sub _STARTTLS { shift->command("STARTTLS")->response() == CMD_MORE }
731
+ sub _STAT { shift->command('STAT', @_)->response == CMD_OK }
732
+ sub _MODE { shift->command('MODE', @_)->response == CMD_OK }
733
+ sub _XGTITLE { shift->command('XGTITLE', @_)->response == CMD_OK }
734
+ sub _XHDR { shift->command('XHDR', @_)->response == CMD_OK }
735
+ sub _XPAT { shift->command('XPAT', @_)->response == CMD_OK }
736
+ sub _XPATH { shift->command('XPATH', @_)->response == CMD_OK }
737
+ sub _XOVER { shift->command('XOVER', @_)->response == CMD_OK }
738
+ sub _XROVER { shift->command('XROVER', @_)->response == CMD_OK }
739
+ sub _XTHREAD { shift->unsupported }
740
+ sub _XSEARCH { shift->unsupported }
741
+ sub _XINDEX { shift->unsupported }
742
+
743
+ ##
744
+ ## IO/perl methods
745
+ ##
746
+
747
+
748
+ sub DESTROY {
749
+ my $nntp = shift;
750
+ defined(fileno($nntp)) && $nntp->quit;
751
+ }
752
+
753
+ {
754
+ package Net::NNTP::_SSL;
755
+ our @ISA = ( $ssl_class ? ($ssl_class):(), 'Net::NNTP' );
756
+ sub starttls { die "NNTP connection is already in SSL mode" }
757
+ sub start_SSL {
758
+ my ($class,$nntp,%arg) = @_;
759
+ delete @arg{ grep { !m{^SSL_} } keys %arg };
760
+ ( $arg{SSL_verifycn_name} ||= $nntp->host )
761
+ =~s{(?<!:):[\w()]+$}{}; # strip port
762
+ $arg{SSL_hostname} = $arg{SSL_verifycn_name}
763
+ if ! defined $arg{SSL_hostname} && $class->can_client_sni;
764
+ my $ok = $class->SUPER::start_SSL($nntp,
765
+ SSL_verifycn_scheme => 'nntp',
766
+ %arg
767
+ );
768
+ $@ = $ssl_class->errstr if !$ok;
769
+ return $ok;
770
+ }
771
+ }
772
+
773
+
774
+
775
+
776
+ 1;
777
+
778
+ __END__
779
+
780
+ =head1 NAME
781
+
782
+ Net::NNTP - NNTP Client class
783
+
784
+ =head1 SYNOPSIS
785
+
786
+ use Net::NNTP;
787
+
788
+ $nntp = Net::NNTP->new("some.host.name");
789
+ $nntp->quit;
790
+
791
+ # start with SSL, e.g. nntps
792
+ $nntp = Net::NNTP->new("some.host.name", SSL => 1);
793
+
794
+ # start with plain and upgrade to SSL
795
+ $nntp = Net::NNTP->new("some.host.name");
796
+ $nntp->starttls;
797
+
798
+
799
+ =head1 DESCRIPTION
800
+
801
+ C<Net::NNTP> is a class implementing a simple NNTP client in Perl as described
802
+ in RFC977 and RFC4642.
803
+ With L<IO::Socket::SSL> installed it also provides support for implicit and
804
+ explicit TLS encryption, i.e. NNTPS or NNTP+STARTTLS.
805
+
806
+ The Net::NNTP class is a subclass of Net::Cmd and (depending on avaibility) of
807
+ IO::Socket::IP, IO::Socket::INET6 or IO::Socket::INET.
808
+
809
+ =head2 Class Methods
810
+
811
+ =over 4
812
+
813
+ =item C<new([$host][, %options])>
814
+
815
+ This is the constructor for a new Net::NNTP object. C<$host> is the
816
+ name of the remote host to which a NNTP connection is required. If not
817
+ given then it may be passed as the C<Host> option described below. If no host is passed
818
+ then two environment variables are checked, first C<NNTPSERVER> then
819
+ C<NEWSHOST>, then C<Net::Config> is checked, and if a host is not found
820
+ then C<news> is used.
821
+
822
+ C<%options> are passed in a hash like fashion, using key and value pairs.
823
+ Possible options are:
824
+
825
+ B<Host> - NNTP host to connect to. It may be a single scalar, as defined for
826
+ the C<PeerAddr> option in L<IO::Socket::INET>, or a reference to
827
+ an array with hosts to try in turn. The L</host> method will return the value
828
+ which was used to connect to the host.
829
+
830
+ B<Port> - port to connect to.
831
+ Default - 119 for plain NNTP and 563 for immediate SSL (nntps).
832
+
833
+ B<SSL> - If the connection should be done from start with SSL, contrary to later
834
+ upgrade with C<starttls>.
835
+ You can use SSL arguments as documented in L<IO::Socket::SSL>, but it will
836
+ usually use the right arguments already.
837
+
838
+ B<Timeout> - Maximum time, in seconds, to wait for a response from the
839
+ NNTP server, a value of zero will cause all IO operations to block.
840
+ (default: 120)
841
+
842
+ B<Debug> - Enable the printing of debugging information to STDERR
843
+
844
+ B<Reader> - If the remote server is INN then initially the connection
845
+ will be to innd, by default C<Net::NNTP> will issue a C<MODE READER> command
846
+ so that the remote server becomes nnrpd. If the C<Reader> option is given
847
+ with a value of zero, then this command will not be sent and the
848
+ connection will be left talking to innd.
849
+
850
+ B<LocalAddr> and B<LocalPort> - These parameters are passed directly
851
+ to IO::Socket to allow binding the socket to a specific local address and port.
852
+
853
+ B<Domain> - This parameter is passed directly to IO::Socket and makes it
854
+ possible to enforce IPv4 connections even if L<IO::Socket::IP> is used as super
855
+ class. Alternatively B<Family> can be used.
856
+
857
+ =back
858
+
859
+ =head2 Object Methods
860
+
861
+ Unless otherwise stated all methods return either a I<true> or I<false>
862
+ value, with I<true> meaning that the operation was a success. When a method
863
+ states that it returns a value, failure will be returned as I<undef> or an
864
+ empty list.
865
+
866
+ C<Net::NNTP> inherits from C<Net::Cmd> so methods defined in C<Net::Cmd> may
867
+ be used to send commands to the remote NNTP server in addition to the methods
868
+ documented here.
869
+
870
+ =over 4
871
+
872
+ =item C<host()>
873
+
874
+ Returns the value used by the constructor, and passed to IO::Socket::INET,
875
+ to connect to the host.
876
+
877
+ =item C<starttls()>
878
+
879
+ Upgrade existing plain connection to SSL.
880
+ Any arguments necessary for SSL must be given in C<new> already.
881
+
882
+ =item C<article([{$msgid|$msgnum}[, $fh]])>
883
+
884
+ Retrieve the header, a blank line, then the body (text) of the
885
+ specified article.
886
+
887
+ If C<$fh> is specified then it is expected to be a valid filehandle
888
+ and the result will be printed to it, on success a true value will be
889
+ returned. If C<$fh> is not specified then the return value, on success,
890
+ will be a reference to an array containing the article requested, each
891
+ entry in the array will contain one line of the article.
892
+
893
+ If no arguments are passed then the current article in the currently
894
+ selected newsgroup is fetched.
895
+
896
+ C<$msgnum> is a numeric id of an article in the current newsgroup, and
897
+ will change the current article pointer. C<$msgid> is the message id of
898
+ an article as shown in that article's header. It is anticipated that the
899
+ client will obtain the C<$msgid> from a list provided by the C<newnews>
900
+ command, from references contained within another article, or from the
901
+ message-id provided in the response to some other commands.
902
+
903
+ If there is an error then C<undef> will be returned.
904
+
905
+ =item C<body([{$msgid|$msgnum}[, [$fh]])>
906
+
907
+ Like C<article> but only fetches the body of the article.
908
+
909
+ =item C<head([{$msgid|$msgnum}[, [$fh]])>
910
+
911
+ Like C<article> but only fetches the headers for the article.
912
+
913
+ =item C<articlefh([{$msgid|$msgnum}])>
914
+
915
+ =item C<bodyfh([{$msgid|$msgnum}])>
916
+
917
+ =item C<headfh([{$msgid|$msgnum}])>
918
+
919
+ These are similar to article(), body() and head(), but rather than
920
+ returning the requested data directly, they return a tied filehandle
921
+ from which to read the article.
922
+
923
+ =item C<nntpstat([{$msgid|$msgnum}])>
924
+
925
+ The C<nntpstat> command is similar to the C<article> command except that no
926
+ text is returned. When selecting by message number within a group,
927
+ the C<nntpstat> command serves to set the "current article pointer" without
928
+ sending text.
929
+
930
+ Using the C<nntpstat> command to
931
+ select by message-id is valid but of questionable value, since a
932
+ selection by message-id does B<not> alter the "current article pointer".
933
+
934
+ Returns the message-id of the "current article".
935
+
936
+ =item C<group([$group])>
937
+
938
+ Set and/or get the current group. If C<$group> is not given then information
939
+ is returned on the current group.
940
+
941
+ In a scalar context it returns the group name.
942
+
943
+ In an array context the return value is a list containing, the number
944
+ of articles in the group, the number of the first article, the number
945
+ of the last article and the group name.
946
+
947
+ =item C<help()>
948
+
949
+ Request help text (a short summary of commands that are understood by this
950
+ implementation) from the server. Returns the text or undef upon failure.
951
+
952
+ =item C<ihave($msgid[, $message])>
953
+
954
+ The C<ihave> command informs the server that the client has an article
955
+ whose id is C<$msgid>. If the server desires a copy of that
956
+ article and C<$message> has been given then it will be sent.
957
+
958
+ Returns I<true> if the server desires the article and C<$message> was
959
+ successfully sent, if specified.
960
+
961
+ If C<$message> is not specified then the message must be sent using the
962
+ C<datasend> and C<dataend> methods from L<Net::Cmd>
963
+
964
+ C<$message> can be either an array of lines or a reference to an array
965
+ and must be encoded by the caller to octets of whatever encoding is required,
966
+ e.g. by using the Encode module's C<encode()> function.
967
+
968
+ =item C<last()>
969
+
970
+ Set the "current article pointer" to the previous article in the current
971
+ newsgroup.
972
+
973
+ Returns the message-id of the article.
974
+
975
+ =item C<date()>
976
+
977
+ Returns the date on the remote server. This date will be in a UNIX time
978
+ format (seconds since 1970)
979
+
980
+ =item C<postok()>
981
+
982
+ C<postok> will return I<true> if the servers initial response indicated
983
+ that it will allow posting.
984
+
985
+ =item C<authinfo($user, $pass)>
986
+
987
+ Authenticates to the server (using the original AUTHINFO USER / AUTHINFO PASS
988
+ form, defined in RFC2980) using the supplied username and password. Please
989
+ note that the password is sent in clear text to the server. This command
990
+ should not be used with valuable passwords unless the connection to the server
991
+ is somehow protected.
992
+
993
+ =item C<authinfo_simple($user, $pass)>
994
+
995
+ Authenticates to the server (using the proposed NNTP V2 AUTHINFO SIMPLE form,
996
+ defined and deprecated in RFC2980) using the supplied username and password.
997
+ As with L</authinfo> the password is sent in clear text.
998
+
999
+ =item C<list()>
1000
+
1001
+ Obtain information about all the active newsgroups. The results is a reference
1002
+ to a hash where the key is a group name and each value is a reference to an
1003
+ array. The elements in this array are:- the last article number in the group,
1004
+ the first article number in the group and any information flags about the group.
1005
+
1006
+ =item C<newgroups($since[, $distributions])>
1007
+
1008
+ C<$since> is a time value and C<$distributions> is either a distribution
1009
+ pattern or a reference to a list of distribution patterns.
1010
+ The result is the same as C<list>, but the
1011
+ groups return will be limited to those created after C<$since> and, if
1012
+ specified, in one of the distribution areas in C<$distributions>.
1013
+
1014
+ =item C<newnews($since[, $groups[, $distributions]])>
1015
+
1016
+ C<$since> is a time value. C<$groups> is either a group pattern or a reference
1017
+ to a list of group patterns. C<$distributions> is either a distribution
1018
+ pattern or a reference to a list of distribution patterns.
1019
+
1020
+ Returns a reference to a list which contains the message-ids of all news posted
1021
+ after C<$since>, that are in a groups which matched C<$groups> and a
1022
+ distribution which matches C<$distributions>.
1023
+
1024
+ =item C<next()>
1025
+
1026
+ Set the "current article pointer" to the next article in the current
1027
+ newsgroup.
1028
+
1029
+ Returns the message-id of the article.
1030
+
1031
+ =item C<post([$message])>
1032
+
1033
+ Post a new article to the news server. If C<$message> is specified and posting
1034
+ is allowed then the message will be sent.
1035
+
1036
+ If C<$message> is not specified then the message must be sent using the
1037
+ C<datasend> and C<dataend> methods from L<Net::Cmd>
1038
+
1039
+ C<$message> can be either an array of lines or a reference to an array
1040
+ and must be encoded by the caller to octets of whatever encoding is required,
1041
+ e.g. by using the Encode module's C<encode()> function.
1042
+
1043
+ The message, either sent via C<datasend> or as the C<$message>
1044
+ parameter, must be in the format as described by RFC822 and must
1045
+ contain From:, Newsgroups: and Subject: headers.
1046
+
1047
+ =item C<postfh()>
1048
+
1049
+ Post a new article to the news server using a tied filehandle. If
1050
+ posting is allowed, this method will return a tied filehandle that you
1051
+ can print() the contents of the article to be posted. You must
1052
+ explicitly close() the filehandle when you are finished posting the
1053
+ article, and the return value from the close() call will indicate
1054
+ whether the message was successfully posted.
1055
+
1056
+ =item C<slave()>
1057
+
1058
+ Tell the remote server that I am not a user client, but probably another
1059
+ news server.
1060
+
1061
+ =item C<quit()>
1062
+
1063
+ Quit the remote server and close the socket connection.
1064
+
1065
+ =item C<can_inet6()>
1066
+
1067
+ Returns whether we can use IPv6.
1068
+
1069
+ =item C<can_ssl()>
1070
+
1071
+ Returns whether we can use SSL.
1072
+
1073
+ =back
1074
+
1075
+ =head2 Extension Methods
1076
+
1077
+ These methods use commands that are not part of the RFC977 documentation. Some
1078
+ servers may not support all of them.
1079
+
1080
+ =over 4
1081
+
1082
+ =item C<newsgroups([$pattern])>
1083
+
1084
+ Returns a reference to a hash where the keys are all the group names which
1085
+ match C<$pattern>, or all of the groups if no pattern is specified, and
1086
+ each value contains the description text for the group.
1087
+
1088
+ =item C<distributions()>
1089
+
1090
+ Returns a reference to a hash where the keys are all the possible
1091
+ distribution names and the values are the distribution descriptions.
1092
+
1093
+ =item C<distribution_patterns()>
1094
+
1095
+ Returns a reference to an array where each element, itself an array
1096
+ reference, consists of the three fields of a line of the distrib.pats list
1097
+ maintained by some NNTP servers, namely: a weight, a wildmat and a value
1098
+ which the client may use to construct a Distribution header.
1099
+
1100
+ =item C<subscriptions()>
1101
+
1102
+ Returns a reference to a list which contains a list of groups which
1103
+ are recommended for a new user to subscribe to.
1104
+
1105
+ =item C<overview_fmt()>
1106
+
1107
+ Returns a reference to an array which contain the names of the fields returned
1108
+ by C<xover>.
1109
+
1110
+ =item C<active_times()>
1111
+
1112
+ Returns a reference to a hash where the keys are the group names and each
1113
+ value is a reference to an array containing the time the groups was created
1114
+ and an identifier, possibly an Email address, of the creator.
1115
+
1116
+ =item C<active([$pattern])>
1117
+
1118
+ Similar to C<list> but only active groups that match the pattern are returned.
1119
+ C<$pattern> can be a group pattern.
1120
+
1121
+ =item C<xgtitle($pattern)>
1122
+
1123
+ Returns a reference to a hash where the keys are all the group names which
1124
+ match C<$pattern> and each value is the description text for the group.
1125
+
1126
+ =item C<xhdr($header, $message_spec)>
1127
+
1128
+ Obtain the header field C<$header> for all the messages specified.
1129
+
1130
+ The return value will be a reference
1131
+ to a hash where the keys are the message numbers and each value contains
1132
+ the text of the requested header for that message.
1133
+
1134
+ =item C<xover($message_spec)>
1135
+
1136
+ The return value will be a reference
1137
+ to a hash where the keys are the message numbers and each value contains
1138
+ a reference to an array which contains the overview fields for that
1139
+ message.
1140
+
1141
+ The names of the fields can be obtained by calling C<overview_fmt>.
1142
+
1143
+ =item C<xpath($message_id)>
1144
+
1145
+ Returns the path name to the file on the server which contains the specified
1146
+ message.
1147
+
1148
+ =item C<xpat($header, $pattern, $message_spec)>
1149
+
1150
+ The result is the same as C<xhdr> except the is will be restricted to
1151
+ headers where the text of the header matches C<$pattern>
1152
+
1153
+ =item C<xrover($message_spec)>
1154
+
1155
+ The XROVER command returns reference information for the article(s)
1156
+ specified.
1157
+
1158
+ Returns a reference to a HASH where the keys are the message numbers and the
1159
+ values are the References: lines from the articles
1160
+
1161
+ =item C<listgroup([$group])>
1162
+
1163
+ Returns a reference to a list of all the active messages in C<$group>, or
1164
+ the current group if C<$group> is not specified.
1165
+
1166
+ =item C<reader()>
1167
+
1168
+ Tell the server that you are a reader and not another server.
1169
+
1170
+ This is required by some servers. For example if you are connecting to
1171
+ an INN server and you have transfer permission your connection will
1172
+ be connected to the transfer daemon, not the NNTP daemon. Issuing
1173
+ this command will cause the transfer daemon to hand over control
1174
+ to the NNTP daemon.
1175
+
1176
+ Some servers do not understand this command, but issuing it and ignoring
1177
+ the response is harmless.
1178
+
1179
+ =back
1180
+
1181
+ =head2 Unsupported
1182
+
1183
+ The following NNTP command are unsupported by the package, and there are
1184
+ no plans to do so.
1185
+
1186
+ AUTHINFO GENERIC
1187
+ XTHREAD
1188
+ XSEARCH
1189
+ XINDEX
1190
+
1191
+ =head2 Definitions
1192
+
1193
+ =over 4
1194
+
1195
+ =item $message_spec
1196
+
1197
+ C<$message_spec> is either a single message-id, a single message number, or
1198
+ a reference to a list of two message numbers.
1199
+
1200
+ If C<$message_spec> is a reference to a list of two message numbers and the
1201
+ second number in a range is less than or equal to the first then the range
1202
+ represents all messages in the group after the first message number.
1203
+
1204
+ B<NOTE> For compatibility reasons only with earlier versions of Net::NNTP
1205
+ a message spec can be passed as a list of two numbers, this is deprecated
1206
+ and a reference to the list should now be passed
1207
+
1208
+ =item $pattern
1209
+
1210
+ The C<NNTP> protocol uses the C<WILDMAT> format for patterns.
1211
+ The WILDMAT format was first developed by Rich Salz based on
1212
+ the format used in the UNIX "find" command to articulate
1213
+ file names. It was developed to provide a uniform mechanism
1214
+ for matching patterns in the same manner that the UNIX shell
1215
+ matches filenames.
1216
+
1217
+ Patterns are implicitly anchored at the
1218
+ beginning and end of each string when testing for a match.
1219
+
1220
+ There are five pattern matching operations other than a strict
1221
+ one-to-one match between the pattern and the source to be
1222
+ checked for a match.
1223
+
1224
+ The first is an asterisk C<*> to match any sequence of zero or more
1225
+ characters.
1226
+
1227
+ The second is a question mark C<?> to match any single character. The
1228
+ third specifies a specific set of characters.
1229
+
1230
+ The set is specified as a list of characters, or as a range of characters
1231
+ where the beginning and end of the range are separated by a minus (or dash)
1232
+ character, or as any combination of lists and ranges. The dash can
1233
+ also be included in the set as a character it if is the beginning
1234
+ or end of the set. This set is enclosed in square brackets. The
1235
+ close square bracket C<]> may be used in a set if it is the first
1236
+ character in the set.
1237
+
1238
+ The fourth operation is the same as the
1239
+ logical not of the third operation and is specified the same
1240
+ way as the third with the addition of a caret character C<^> at
1241
+ the beginning of the test string just inside the open square
1242
+ bracket.
1243
+
1244
+ The final operation uses the backslash character to
1245
+ invalidate the special meaning of an open square bracket C<[>,
1246
+ the asterisk, backslash or the question mark. Two backslashes in
1247
+ sequence will result in the evaluation of the backslash as a
1248
+ character with no special meaning.
1249
+
1250
+ =over 4
1251
+
1252
+ =item Examples
1253
+
1254
+ =item C<[^]-]>
1255
+
1256
+ matches any single character other than a close square
1257
+ bracket or a minus sign/dash.
1258
+
1259
+ =item C<*bdc>
1260
+
1261
+ matches any string that ends with the string "bdc"
1262
+ including the string "bdc" (without quotes).
1263
+
1264
+ =item C<[0-9a-zA-Z]>
1265
+
1266
+ matches any single printable alphanumeric ASCII character.
1267
+
1268
+ =item C<a??d>
1269
+
1270
+ matches any four character string which begins
1271
+ with a and ends with d.
1272
+
1273
+ =back
1274
+
1275
+ =back
1276
+
1277
+ =head1 EXPORTS
1278
+
1279
+ I<None>.
1280
+
1281
+ =head1 KNOWN BUGS
1282
+
1283
+ See L<https://rt.cpan.org/Dist/Display.html?Status=Active&Queue=libnet>.
1284
+
1285
+ =head1 SEE ALSO
1286
+
1287
+ L<Net::Cmd>,
1288
+ L<IO::Socket::SSL>.
1289
+
1290
+ =head1 AUTHOR
1291
+
1292
+ Graham Barr E<lt>L<gbarr@pobox.com|mailto:gbarr@pobox.com>E<gt>.
1293
+
1294
+ Steve Hay E<lt>L<shay@cpan.org|mailto:shay@cpan.org>E<gt> is now maintaining
1295
+ libnet as of version 1.22_02.
1296
+
1297
+ =head1 COPYRIGHT
1298
+
1299
+ Copyright (C) 1995-1997 Graham Barr. All rights reserved.
1300
+
1301
+ Copyright (C) 2013-2016, 2020 Steve Hay. All rights reserved.
1302
+
1303
+ =head1 LICENCE
1304
+
1305
+ This module is free software; you can redistribute it and/or modify it under the
1306
+ same terms as Perl itself, i.e. under the terms of either the GNU General Public
1307
+ License or the Artistic License, as specified in the F<LICENCE> file.
1308
+
1309
+ =head1 VERSION
1310
+
1311
+ Version 3.15
1312
+
1313
+ =head1 DATE
1314
+
1315
+ 20 March 2023
1316
+
1317
+ =head1 HISTORY
1318
+
1319
+ See the F<Changes> file.
1320
+
1321
+ =cut
git/usr/share/perl5/core_perl/Net/Netrc.pm ADDED
@@ -0,0 +1,366 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Net::Netrc.pm
2
+ #
3
+ # Copyright (C) 1995-1998 Graham Barr. All rights reserved.
4
+ # Copyright (C) 2013-2014, 2020 Steve Hay. All rights reserved.
5
+ # This module is free software; you can redistribute it and/or modify it under
6
+ # the same terms as Perl itself, i.e. under the terms of either the GNU General
7
+ # Public License or the Artistic License, as specified in the F<LICENCE> file.
8
+
9
+ package Net::Netrc;
10
+
11
+ use 5.008001;
12
+
13
+ use strict;
14
+ use warnings;
15
+
16
+ use Carp;
17
+ use FileHandle;
18
+
19
+ our $VERSION = "3.15";
20
+
21
+ our $TESTING;
22
+
23
+ my %netrc = ();
24
+
25
+ sub _readrc {
26
+ my($class, $host) = @_;
27
+ my ($home, $file);
28
+
29
+ if ($^O eq "MacOS") {
30
+ $home = $ENV{HOME} || `pwd`;
31
+ chomp($home);
32
+ $file = ($home =~ /:$/ ? $home . "netrc" : $home . ":netrc");
33
+ }
34
+ else {
35
+
36
+ # Some OS's don't have "getpwuid", so we default to $ENV{HOME}
37
+ $home = eval { (getpwuid($>))[7] } || $ENV{HOME};
38
+ $home ||= $ENV{HOMEDRIVE} . ($ENV{HOMEPATH} || '') if defined $ENV{HOMEDRIVE};
39
+ if (-e $home . "/.netrc") {
40
+ $file = $home . "/.netrc";
41
+ }
42
+ elsif (-e $home . "/_netrc") {
43
+ $file = $home . "/_netrc";
44
+ }
45
+ else {
46
+ return unless $TESTING;
47
+ }
48
+ }
49
+
50
+ my ($login, $pass, $acct) = (undef, undef, undef);
51
+ my $fh;
52
+ local $_;
53
+
54
+ $netrc{default} = undef;
55
+
56
+ # OS/2 and Win32 do not handle stat in a way compatible with this check :-(
57
+ unless ($^O eq 'os2'
58
+ || $^O eq 'MSWin32'
59
+ || $^O eq 'MacOS'
60
+ || $^O =~ /^cygwin/)
61
+ {
62
+ my @stat = stat($file);
63
+
64
+ if (@stat) {
65
+ if ($stat[2] & 077) { ## no critic (ValuesAndExpressions::ProhibitLeadingZeros)
66
+ carp "Bad permissions: $file";
67
+ return;
68
+ }
69
+ if ($stat[4] != $<) {
70
+ carp "Not owner: $file";
71
+ return;
72
+ }
73
+ }
74
+ }
75
+
76
+ if ($fh = FileHandle->new($file, "r")) {
77
+ my ($mach, $macdef, $tok, @tok) = (0, 0);
78
+
79
+ while (<$fh>) {
80
+ undef $macdef if /\A\n\Z/;
81
+
82
+ if ($macdef) {
83
+ push(@$macdef, $_);
84
+ next;
85
+ }
86
+
87
+ s/^\s*//;
88
+ chomp;
89
+
90
+ while (length && s/^("((?:[^"]+|\\.)*)"|((?:[^\\\s]+|\\.)*))\s*//) {
91
+ (my $tok = $+) =~ s/\\(.)/$1/g;
92
+ push(@tok, $tok);
93
+ }
94
+
95
+ TOKEN:
96
+ while (@tok) {
97
+ if ($tok[0] eq "default") {
98
+ shift(@tok);
99
+ $mach = bless {}, $class;
100
+ $netrc{default} = [$mach];
101
+
102
+ next TOKEN;
103
+ }
104
+
105
+ last TOKEN
106
+ unless @tok > 1;
107
+
108
+ $tok = shift(@tok);
109
+
110
+ if ($tok eq "machine") {
111
+ my $host = shift @tok;
112
+ $mach = bless {machine => $host}, $class;
113
+
114
+ $netrc{$host} = []
115
+ unless exists($netrc{$host});
116
+ push(@{$netrc{$host}}, $mach);
117
+ }
118
+ elsif ($tok =~ /^(login|password|account)$/) {
119
+ next TOKEN unless $mach;
120
+ my $value = shift @tok;
121
+
122
+ # Following line added by rmerrell to remove '/' escape char in .netrc
123
+ $value =~ s/\/\\/\\/g;
124
+ $mach->{$1} = $value;
125
+ }
126
+ elsif ($tok eq "macdef") {
127
+ next TOKEN unless $mach;
128
+ my $value = shift @tok;
129
+ $mach->{macdef} = {}
130
+ unless exists $mach->{macdef};
131
+ $macdef = $mach->{machdef}{$value} = [];
132
+ }
133
+ }
134
+ }
135
+ $fh->close();
136
+ }
137
+ }
138
+
139
+
140
+ sub lookup {
141
+ my ($class, $mach, $login) = @_;
142
+
143
+ $class->_readrc()
144
+ unless exists $netrc{default};
145
+
146
+ $mach ||= 'default';
147
+ undef $login
148
+ if $mach eq 'default';
149
+
150
+ if (exists $netrc{$mach}) {
151
+ if (defined $login) {
152
+ foreach my $m (@{$netrc{$mach}}) {
153
+ return $m
154
+ if (exists $m->{login} && $m->{login} eq $login);
155
+ }
156
+ return;
157
+ }
158
+ return $netrc{$mach}->[0];
159
+ }
160
+
161
+ return $netrc{default}->[0]
162
+ if defined $netrc{default};
163
+
164
+ return;
165
+ }
166
+
167
+
168
+ sub login {
169
+ my $me = shift;
170
+
171
+ exists $me->{login}
172
+ ? $me->{login}
173
+ : undef;
174
+ }
175
+
176
+
177
+ sub account {
178
+ my $me = shift;
179
+
180
+ exists $me->{account}
181
+ ? $me->{account}
182
+ : undef;
183
+ }
184
+
185
+
186
+ sub password {
187
+ my $me = shift;
188
+
189
+ exists $me->{password}
190
+ ? $me->{password}
191
+ : undef;
192
+ }
193
+
194
+
195
+ sub lpa {
196
+ my $me = shift;
197
+ ($me->login, $me->password, $me->account);
198
+ }
199
+
200
+ 1;
201
+
202
+ __END__
203
+
204
+ =head1 NAME
205
+
206
+ Net::Netrc - OO interface to users netrc file
207
+
208
+ =head1 SYNOPSIS
209
+
210
+ use Net::Netrc;
211
+
212
+ $mach = Net::Netrc->lookup('some.machine');
213
+ $login = $mach->login;
214
+ ($login, $password, $account) = $mach->lpa;
215
+
216
+ =head1 DESCRIPTION
217
+
218
+ C<Net::Netrc> is a class implementing a simple interface to the .netrc file
219
+ used as by the ftp program.
220
+
221
+ C<Net::Netrc> also implements security checks just like the ftp program,
222
+ these checks are, first that the .netrc file must be owned by the user and
223
+ second the ownership permissions should be such that only the owner has
224
+ read and write access. If these conditions are not met then a warning is
225
+ output and the .netrc file is not read.
226
+
227
+ =head2 The F<.netrc> File
228
+
229
+ The .netrc file contains login and initialization information used by the
230
+ auto-login process. It resides in the user's home directory. The following
231
+ tokens are recognized; they may be separated by spaces, tabs, or new-lines:
232
+
233
+ =over 4
234
+
235
+ =item machine name
236
+
237
+ Identify a remote machine name. The auto-login process searches
238
+ the .netrc file for a machine token that matches the remote machine
239
+ specified. Once a match is made, the subsequent .netrc tokens
240
+ are processed, stopping when the end of file is reached or an-
241
+ other machine or a default token is encountered.
242
+
243
+ =item default
244
+
245
+ This is the same as machine name except that default matches
246
+ any name. There can be only one default token, and it must be
247
+ after all machine tokens. This is normally used as:
248
+
249
+ default login anonymous password user@site
250
+
251
+ thereby giving the user automatic anonymous login to machines
252
+ not specified in .netrc.
253
+
254
+ =item login name
255
+
256
+ Identify a user on the remote machine. If this token is present,
257
+ the auto-login process will initiate a login using the
258
+ specified name.
259
+
260
+ =item password string
261
+
262
+ Supply a password. If this token is present, the auto-login
263
+ process will supply the specified string if the remote server
264
+ requires a password as part of the login process.
265
+
266
+ =item account string
267
+
268
+ Supply an additional account password. If this token is present,
269
+ the auto-login process will supply the specified string
270
+ if the remote server requires an additional account password.
271
+
272
+ =item macdef name
273
+
274
+ Define a macro. C<Net::Netrc> only parses this field to be compatible
275
+ with I<ftp>.
276
+
277
+ =back
278
+
279
+ =head2 Class Methods
280
+
281
+ The constructor for a C<Net::Netrc> object is not called new as it does not
282
+ really create a new object. But instead is called C<lookup> as this is
283
+ essentially what it does.
284
+
285
+ =over 4
286
+
287
+ =item C<lookup($machine[, $login])>
288
+
289
+ Lookup and return a reference to the entry for C<$machine>. If C<$login> is given
290
+ then the entry returned will have the given login. If C<$login> is not given then
291
+ the first entry in the .netrc file for C<$machine> will be returned.
292
+
293
+ If a matching entry cannot be found, and a default entry exists, then a
294
+ reference to the default entry is returned.
295
+
296
+ If there is no matching entry found and there is no default defined, or
297
+ no .netrc file is found, then C<undef> is returned.
298
+
299
+ =back
300
+
301
+ =head2 Object Methods
302
+
303
+ =over 4
304
+
305
+ =item C<login()>
306
+
307
+ Return the login id for the netrc entry
308
+
309
+ =item C<password()>
310
+
311
+ Return the password for the netrc entry
312
+
313
+ =item C<account()>
314
+
315
+ Return the account information for the netrc entry
316
+
317
+ =item C<lpa()>
318
+
319
+ Return a list of login, password and account information for the netrc entry
320
+
321
+ =back
322
+
323
+ =head1 EXPORTS
324
+
325
+ I<None>.
326
+
327
+ =head1 KNOWN BUGS
328
+
329
+ See L<https://rt.cpan.org/Dist/Display.html?Status=Active&Queue=libnet>.
330
+
331
+ =head1 SEE ALSO
332
+
333
+ L<Net::Cmd>.
334
+
335
+ =head1 AUTHOR
336
+
337
+ Graham Barr E<lt>L<gbarr@pobox.com|mailto:gbarr@pobox.com>E<gt>.
338
+
339
+ Steve Hay E<lt>L<shay@cpan.org|mailto:shay@cpan.org>E<gt> is now maintaining
340
+ libnet as of version 1.22_02.
341
+
342
+ =head1 COPYRIGHT
343
+
344
+ Copyright (C) 1995-1998 Graham Barr. All rights reserved.
345
+
346
+ Copyright (C) 2013-2014, 2020 Steve Hay. All rights reserved.
347
+
348
+ =head1 LICENCE
349
+
350
+ This module is free software; you can redistribute it and/or modify it under the
351
+ same terms as Perl itself, i.e. under the terms of either the GNU General Public
352
+ License or the Artistic License, as specified in the F<LICENCE> file.
353
+
354
+ =head1 VERSION
355
+
356
+ Version 3.15
357
+
358
+ =head1 DATE
359
+
360
+ 20 March 2023
361
+
362
+ =head1 HISTORY
363
+
364
+ See the F<Changes> file.
365
+
366
+ =cut
git/usr/share/perl5/core_perl/Net/POP3.pm ADDED
@@ -0,0 +1,882 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Net::POP3.pm
2
+ #
3
+ # Copyright (C) 1995-2004 Graham Barr. All rights reserved.
4
+ # Copyright (C) 2013-2016, 2020 Steve Hay. All rights reserved.
5
+ # This module is free software; you can redistribute it and/or modify it under
6
+ # the same terms as Perl itself, i.e. under the terms of either the GNU General
7
+ # Public License or the Artistic License, as specified in the F<LICENCE> file.
8
+
9
+ package Net::POP3;
10
+
11
+ use 5.008001;
12
+
13
+ use strict;
14
+ use warnings;
15
+
16
+ use Carp;
17
+ use IO::Socket;
18
+ use Net::Cmd;
19
+ use Net::Config;
20
+
21
+ our $VERSION = "3.15";
22
+
23
+ # Code for detecting if we can use SSL
24
+ my $ssl_class = eval {
25
+ require IO::Socket::SSL;
26
+ # first version with default CA on most platforms
27
+ no warnings 'numeric';
28
+ IO::Socket::SSL->VERSION(2.007);
29
+ } && 'IO::Socket::SSL';
30
+
31
+ my $nossl_warn = !$ssl_class &&
32
+ 'To use SSL please install IO::Socket::SSL with version>=2.007';
33
+
34
+ # Code for detecting if we can use IPv6
35
+ my $family_key = 'Domain';
36
+ my $inet6_class = eval {
37
+ require IO::Socket::IP;
38
+ no warnings 'numeric';
39
+ IO::Socket::IP->VERSION(0.25) || die;
40
+ $family_key = 'Family';
41
+ } && 'IO::Socket::IP' || eval {
42
+ require IO::Socket::INET6;
43
+ no warnings 'numeric';
44
+ IO::Socket::INET6->VERSION(2.62);
45
+ } && 'IO::Socket::INET6';
46
+
47
+
48
+ sub can_ssl { $ssl_class };
49
+ sub can_inet6 { $inet6_class };
50
+
51
+ our @ISA = ('Net::Cmd', $inet6_class || 'IO::Socket::INET');
52
+
53
+ sub new {
54
+ my $self = shift;
55
+ my $type = ref($self) || $self;
56
+ my ($host, %arg);
57
+ if (@_ % 2) {
58
+ $host = shift;
59
+ %arg = @_;
60
+ }
61
+ else {
62
+ %arg = @_;
63
+ $host = delete $arg{Host};
64
+ }
65
+ my $hosts = defined $host ? [$host] : $NetConfig{pop3_hosts};
66
+ my $obj;
67
+
68
+ if ($arg{SSL}) {
69
+ # SSL from start
70
+ die $nossl_warn if !$ssl_class;
71
+ $arg{Port} ||= 995;
72
+ }
73
+
74
+ $arg{Timeout} = 120 if ! defined $arg{Timeout};
75
+
76
+ foreach my $h (@{$hosts}) {
77
+ $obj = $type->SUPER::new(
78
+ PeerAddr => ($host = $h),
79
+ PeerPort => $arg{Port} || 'pop3(110)',
80
+ Proto => 'tcp',
81
+ $family_key => $arg{Domain} || $arg{Family},
82
+ LocalAddr => $arg{LocalAddr},
83
+ LocalPort => exists($arg{ResvPort}) ? $arg{ResvPort} : $arg{LocalPort},
84
+ Timeout => $arg{Timeout},
85
+ )
86
+ and last;
87
+ }
88
+
89
+ return
90
+ unless defined $obj;
91
+
92
+ ${*$obj}{'net_pop3_arg'} = \%arg;
93
+ ${*$obj}{'net_pop3_host'} = $host;
94
+ if ($arg{SSL}) {
95
+ Net::POP3::_SSL->start_SSL($obj,%arg) or return;
96
+ }
97
+
98
+ $obj->autoflush(1);
99
+ $obj->debug(exists $arg{Debug} ? $arg{Debug} : undef);
100
+
101
+ unless ($obj->response() == CMD_OK) {
102
+ $obj->close();
103
+ return;
104
+ }
105
+
106
+ ${*$obj}{'net_pop3_banner'} = $obj->message;
107
+
108
+ $obj;
109
+ }
110
+
111
+
112
+ sub host {
113
+ my $me = shift;
114
+ ${*$me}{'net_pop3_host'};
115
+ }
116
+
117
+ ##
118
+ ## We don't want people sending me their passwords when they report problems
119
+ ## now do we :-)
120
+ ##
121
+
122
+
123
+ sub debug_text { $_[2] =~ /^(pass|rpop)/i ? "$1 ....\n" : $_[2]; }
124
+
125
+
126
+ sub login {
127
+ @_ >= 1 && @_ <= 3 or croak 'usage: $pop3->login([$user[, $pass]])';
128
+ my ($me, $user, $pass) = @_;
129
+
130
+ if (@_ <= 2) {
131
+ ($user, $pass) = $me->_lookup_credentials($user);
132
+ }
133
+
134
+ $me->user($user)
135
+ and $me->pass($pass);
136
+ }
137
+
138
+ sub starttls {
139
+ my $self = shift;
140
+ $ssl_class or die $nossl_warn;
141
+ $self->_STLS or return;
142
+ Net::POP3::_SSL->start_SSL($self,
143
+ %{ ${*$self}{'net_pop3_arg'} }, # (ssl) args given in new
144
+ @_ # more (ssl) args
145
+ ) or return;
146
+ return 1;
147
+ }
148
+
149
+ sub apop {
150
+ @_ >= 1 && @_ <= 3 or croak 'usage: $pop3->apop([$user[, $pass]])';
151
+ my ($me, $user, $pass) = @_;
152
+ my $banner;
153
+ my $md;
154
+
155
+ if (eval { local $SIG{__DIE__}; require Digest::MD5 }) {
156
+ $md = Digest::MD5->new();
157
+ }
158
+ elsif (eval { local $SIG{__DIE__}; require MD5 }) {
159
+ $md = MD5->new();
160
+ }
161
+ else {
162
+ carp "You need to install Digest::MD5 or MD5 to use the APOP command";
163
+ return;
164
+ }
165
+
166
+ return
167
+ unless ($banner = (${*$me}{'net_pop3_banner'} =~ /(<.*>)/)[0]);
168
+
169
+ if (@_ <= 2) {
170
+ ($user, $pass) = $me->_lookup_credentials($user);
171
+ }
172
+
173
+ $md->add($banner, $pass);
174
+
175
+ return
176
+ unless ($me->_APOP($user, $md->hexdigest));
177
+
178
+ $me->_get_mailbox_count();
179
+ }
180
+
181
+
182
+ sub user {
183
+ @_ == 2 or croak 'usage: $pop3->user($user)';
184
+ $_[0]->_USER($_[1]) ? 1 : undef;
185
+ }
186
+
187
+
188
+ sub pass {
189
+ @_ == 2 or croak 'usage: $pop3->pass($pass)';
190
+
191
+ my ($me, $pass) = @_;
192
+
193
+ return
194
+ unless ($me->_PASS($pass));
195
+
196
+ $me->_get_mailbox_count();
197
+ }
198
+
199
+
200
+ sub reset {
201
+ @_ == 1 or croak 'usage: $obj->reset()';
202
+
203
+ my $me = shift;
204
+
205
+ return 0
206
+ unless ($me->_RSET);
207
+
208
+ if (defined ${*$me}{'net_pop3_mail'}) {
209
+ local $_;
210
+ foreach (@{${*$me}{'net_pop3_mail'}}) {
211
+ delete $_->{'net_pop3_deleted'};
212
+ }
213
+ }
214
+ }
215
+
216
+
217
+ sub last {
218
+ @_ == 1 or croak 'usage: $obj->last()';
219
+
220
+ return
221
+ unless $_[0]->_LAST && $_[0]->message =~ /(\d+)/;
222
+
223
+ return $1;
224
+ }
225
+
226
+
227
+ sub top {
228
+ @_ == 2 || @_ == 3 or croak 'usage: $pop3->top($msgnum[, $numlines])';
229
+ my $me = shift;
230
+
231
+ return
232
+ unless $me->_TOP($_[0], $_[1] || 0);
233
+
234
+ $me->read_until_dot;
235
+ }
236
+
237
+
238
+ sub popstat {
239
+ @_ == 1 or croak 'usage: $pop3->popstat()';
240
+ my $me = shift;
241
+
242
+ return ()
243
+ unless $me->_STAT && $me->message =~ /(\d+)\D+(\d+)/;
244
+
245
+ ($1 || 0, $2 || 0);
246
+ }
247
+
248
+
249
+ sub list {
250
+ @_ == 1 || @_ == 2 or croak 'usage: $pop3->list([$msgnum])';
251
+ my $me = shift;
252
+
253
+ return
254
+ unless $me->_LIST(@_);
255
+
256
+ if (@_) {
257
+ $me->message =~ /\d+\D+(\d+)/;
258
+ return $1 || undef;
259
+ }
260
+
261
+ my $info = $me->read_until_dot
262
+ or return;
263
+
264
+ my %hash = map { (/(\d+)\D+(\d+)/) } @$info;
265
+
266
+ return \%hash;
267
+ }
268
+
269
+
270
+ sub get {
271
+ @_ == 2 or @_ == 3 or croak 'usage: $pop3->get($msgnum[, $fh])';
272
+ my $me = shift;
273
+
274
+ return
275
+ unless $me->_RETR(shift);
276
+
277
+ $me->read_until_dot(@_);
278
+ }
279
+
280
+
281
+ sub getfh {
282
+ @_ == 2 or croak 'usage: $pop3->getfh($msgnum)';
283
+ my $me = shift;
284
+
285
+ return unless $me->_RETR(shift);
286
+ return $me->tied_fh;
287
+ }
288
+
289
+
290
+ sub delete {
291
+ @_ == 2 or croak 'usage: $pop3->delete($msgnum)';
292
+ my $me = shift;
293
+ return 0 unless $me->_DELE(@_);
294
+ ${*$me}{'net_pop3_deleted'} = 1;
295
+ }
296
+
297
+
298
+ sub uidl {
299
+ @_ == 1 || @_ == 2 or croak 'usage: $pop3->uidl([$msgnum])';
300
+ my $me = shift;
301
+ my $uidl;
302
+
303
+ $me->_UIDL(@_)
304
+ or return;
305
+ if (@_) {
306
+ $uidl = ($me->message =~ /\d+\s+([\041-\176]+)/)[0];
307
+ }
308
+ else {
309
+ my $ref = $me->read_until_dot
310
+ or return;
311
+ $uidl = {};
312
+ foreach my $ln (@$ref) {
313
+ my ($msg, $uid) = $ln =~ /^\s*(\d+)\s+([\041-\176]+)/;
314
+ $uidl->{$msg} = $uid;
315
+ }
316
+ }
317
+ return $uidl;
318
+ }
319
+
320
+
321
+ sub ping {
322
+ @_ == 2 or croak 'usage: $pop3->ping($user)';
323
+ my $me = shift;
324
+
325
+ return () unless $me->_PING(@_) && $me->message =~ /(\d+)\D+(\d+)/;
326
+
327
+ ($1 || 0, $2 || 0);
328
+ }
329
+
330
+
331
+ sub _lookup_credentials {
332
+ my ($me, $user) = @_;
333
+
334
+ require Net::Netrc;
335
+
336
+ $user ||= eval { local $SIG{__DIE__}; (getpwuid($>))[0] }
337
+ || $ENV{NAME}
338
+ || $ENV{USER}
339
+ || $ENV{LOGNAME};
340
+
341
+ my $m = Net::Netrc->lookup(${*$me}{'net_pop3_host'}, $user);
342
+ $m ||= Net::Netrc->lookup(${*$me}{'net_pop3_host'});
343
+
344
+ my $pass = $m
345
+ ? $m->password || ""
346
+ : "";
347
+
348
+ ($user, $pass);
349
+ }
350
+
351
+
352
+ sub _get_mailbox_count {
353
+ my ($me) = @_;
354
+ my $ret = ${*$me}{'net_pop3_count'} =
355
+ ($me->message =~ /(\d+)\s+message/io) ? $1 : ($me->popstat)[0];
356
+
357
+ $ret ? $ret : "0E0";
358
+ }
359
+
360
+
361
+ sub _STAT { shift->command('STAT' )->response() == CMD_OK }
362
+ sub _LIST { shift->command('LIST', @_)->response() == CMD_OK }
363
+ sub _RETR { shift->command('RETR', $_[0])->response() == CMD_OK }
364
+ sub _DELE { shift->command('DELE', $_[0])->response() == CMD_OK }
365
+ sub _NOOP { shift->command('NOOP' )->response() == CMD_OK }
366
+ sub _RSET { shift->command('RSET' )->response() == CMD_OK }
367
+ sub _QUIT { shift->command('QUIT' )->response() == CMD_OK }
368
+ sub _TOP { shift->command( 'TOP', @_)->response() == CMD_OK }
369
+ sub _UIDL { shift->command('UIDL', @_)->response() == CMD_OK }
370
+ sub _USER { shift->command('USER', $_[0])->response() == CMD_OK }
371
+ sub _PASS { shift->command('PASS', $_[0])->response() == CMD_OK }
372
+ sub _APOP { shift->command('APOP', @_)->response() == CMD_OK }
373
+ sub _PING { shift->command('PING', $_[0])->response() == CMD_OK }
374
+ sub _RPOP { shift->command('RPOP', $_[0])->response() == CMD_OK }
375
+ sub _LAST { shift->command('LAST' )->response() == CMD_OK }
376
+ sub _CAPA { shift->command('CAPA' )->response() == CMD_OK }
377
+ sub _STLS { shift->command("STLS", )->response() == CMD_OK }
378
+
379
+
380
+ sub quit {
381
+ my $me = shift;
382
+
383
+ $me->_QUIT;
384
+ $me->close;
385
+ }
386
+
387
+
388
+ sub DESTROY {
389
+ my $me = shift;
390
+
391
+ if (defined fileno($me) and ${*$me}{'net_pop3_deleted'}) {
392
+ $me->reset;
393
+ $me->quit;
394
+ }
395
+ }
396
+
397
+ ##
398
+ ## POP3 has weird responses, so we emulate them to look the same :-)
399
+ ##
400
+
401
+
402
+ sub response {
403
+ my $cmd = shift;
404
+ my $str = $cmd->getline() or return;
405
+ my $code = "500";
406
+
407
+ $cmd->debug_print(0, $str)
408
+ if ($cmd->debug);
409
+
410
+ if ($str =~ s/^\+OK\s*//io) {
411
+ $code = "200";
412
+ }
413
+ elsif ($str =~ s/^\+\s*//io) {
414
+ $code = "300";
415
+ }
416
+ else {
417
+ $str =~ s/^-ERR\s*//io;
418
+ }
419
+
420
+ ${*$cmd}{'net_cmd_resp'} = [$str];
421
+ ${*$cmd}{'net_cmd_code'} = $code;
422
+
423
+ substr($code, 0, 1);
424
+ }
425
+
426
+
427
+ sub capa {
428
+ my $this = shift;
429
+ my ($capa, %capabilities);
430
+
431
+ # Fake a capability here
432
+ $capabilities{APOP} = '' if ($this->banner() =~ /<.*>/);
433
+
434
+ if ($this->_CAPA()) {
435
+ $capabilities{CAPA} = 1;
436
+ $capa = $this->read_until_dot();
437
+ %capabilities = (%capabilities, map {/^\s*(\S+)\s*(.*)/} @$capa);
438
+ }
439
+ else {
440
+
441
+ # Check AUTH for SASL capabilities
442
+ if ($this->command('AUTH')->response() == CMD_OK) {
443
+ my $mechanism = $this->read_until_dot();
444
+ $capabilities{SASL} = join " ", map {m/([A-Z0-9_-]+)/} @{$mechanism};
445
+ }
446
+ }
447
+
448
+ return ${*$this}{'net_pop3e_capabilities'} = \%capabilities;
449
+ }
450
+
451
+
452
+ sub capabilities {
453
+ my $this = shift;
454
+
455
+ ${*$this}{'net_pop3e_capabilities'} || $this->capa;
456
+ }
457
+
458
+
459
+ sub auth {
460
+ my ($self, $username, $password) = @_;
461
+
462
+ eval {
463
+ require MIME::Base64;
464
+ require Authen::SASL;
465
+ } or $self->set_status(500, ["Need MIME::Base64 and Authen::SASL todo auth"]), return 0;
466
+
467
+ my $capa = $self->capa;
468
+ my $mechanisms = $capa->{SASL} || 'CRAM-MD5';
469
+
470
+ my $sasl;
471
+
472
+ if (ref($username) and UNIVERSAL::isa($username, 'Authen::SASL')) {
473
+ $sasl = $username;
474
+ my $user_mech = $sasl->mechanism || '';
475
+ my @user_mech = split(/\s+/, $user_mech);
476
+ my %user_mech;
477
+ @user_mech{@user_mech} = ();
478
+
479
+ my @server_mech = split(/\s+/, $mechanisms);
480
+ my @mech = @user_mech
481
+ ? grep { exists $user_mech{$_} } @server_mech
482
+ : @server_mech;
483
+ unless (@mech) {
484
+ $self->set_status(
485
+ 500,
486
+ [ 'Client SASL mechanisms (',
487
+ join(', ', @user_mech),
488
+ ') do not match the SASL mechnism the server announces (',
489
+ join(', ', @server_mech), ')',
490
+ ]
491
+ );
492
+ return 0;
493
+ }
494
+
495
+ $sasl->mechanism(join(" ", @mech));
496
+ }
497
+ else {
498
+ die "auth(username, password)" if not length $username;
499
+ $sasl = Authen::SASL->new(
500
+ mechanism => $mechanisms,
501
+ callback => {
502
+ user => $username,
503
+ pass => $password,
504
+ authname => $username,
505
+ }
506
+ );
507
+ }
508
+
509
+ # We should probably allow the user to pass the host, but I don't
510
+ # currently know and SASL mechanisms that are used by smtp that need it
511
+ my ($hostname) = split /:/, ${*$self}{'net_pop3_host'};
512
+ my $client = eval { $sasl->client_new('pop', $hostname, 0) };
513
+
514
+ unless ($client) {
515
+ my $mech = $sasl->mechanism;
516
+ $self->set_status(
517
+ 500,
518
+ [ " Authen::SASL failure: $@",
519
+ '(please check if your local Authen::SASL installation',
520
+ "supports mechanism '$mech'"
521
+ ]
522
+ );
523
+ return 0;
524
+ }
525
+
526
+ my ($token) = $client->client_start
527
+ or do {
528
+ my $mech = $client->mechanism;
529
+ $self->set_status(
530
+ 500,
531
+ [ ' Authen::SASL failure: $client->client_start ',
532
+ "mechanism '$mech' hostname #$hostname#",
533
+ $client->error
534
+ ]
535
+ );
536
+ return 0;
537
+ };
538
+
539
+ # We don't support sasl mechanisms that encrypt the socket traffic.
540
+ # todo that we would really need to change the ISA hierarchy
541
+ # so we don't inherit from IO::Socket, but instead hold it in an attribute
542
+
543
+ my @cmd = ("AUTH", $client->mechanism);
544
+ my $code;
545
+
546
+ push @cmd, MIME::Base64::encode_base64($token, '')
547
+ if defined $token and length $token;
548
+
549
+ while (($code = $self->command(@cmd)->response()) == CMD_MORE) {
550
+
551
+ my ($token) = $client->client_step(MIME::Base64::decode_base64(($self->message)[0])) or do {
552
+ $self->set_status(
553
+ 500,
554
+ [ ' Authen::SASL failure: $client->client_step ',
555
+ "mechanism '", $client->mechanism, " hostname #$hostname#, ",
556
+ $client->error
557
+ ]
558
+ );
559
+ return 0;
560
+ };
561
+
562
+ @cmd = (MIME::Base64::encode_base64(defined $token ? $token : '', ''));
563
+ }
564
+
565
+ $code == CMD_OK;
566
+ }
567
+
568
+
569
+ sub banner {
570
+ my $this = shift;
571
+
572
+ return ${*$this}{'net_pop3_banner'};
573
+ }
574
+
575
+ {
576
+ package Net::POP3::_SSL;
577
+ our @ISA = ( $ssl_class ? ($ssl_class):(), 'Net::POP3' );
578
+ sub starttls { die "POP3 connection is already in SSL mode" }
579
+ sub start_SSL {
580
+ my ($class,$pop3,%arg) = @_;
581
+ delete @arg{ grep { !m{^SSL_} } keys %arg };
582
+ ( $arg{SSL_verifycn_name} ||= $pop3->host )
583
+ =~s{(?<!:):[\w()]+$}{}; # strip port
584
+ $arg{SSL_hostname} = $arg{SSL_verifycn_name}
585
+ if ! defined $arg{SSL_hostname} && $class->can_client_sni;
586
+ $arg{SSL_verifycn_scheme} ||= 'pop3';
587
+ my $ok = $class->SUPER::start_SSL($pop3,%arg);
588
+ $@ = $ssl_class->errstr if !$ok;
589
+ return $ok;
590
+ }
591
+ }
592
+
593
+
594
+
595
+ 1;
596
+
597
+ __END__
598
+
599
+ =head1 NAME
600
+
601
+ Net::POP3 - Post Office Protocol 3 Client class (RFC1939)
602
+
603
+ =head1 SYNOPSIS
604
+
605
+ use Net::POP3;
606
+
607
+ # Constructors
608
+ $pop = Net::POP3->new('pop3host');
609
+ $pop = Net::POP3->new('pop3host', Timeout => 60);
610
+ $pop = Net::POP3->new('pop3host', SSL => 1, Timeout => 60);
611
+
612
+ if ($pop->login($username, $password) > 0) {
613
+ my $msgnums = $pop->list; # hashref of msgnum => size
614
+ foreach my $msgnum (keys %$msgnums) {
615
+ my $msg = $pop->get($msgnum);
616
+ print @$msg;
617
+ $pop->delete($msgnum);
618
+ }
619
+ }
620
+
621
+ $pop->quit;
622
+
623
+ =head1 DESCRIPTION
624
+
625
+ This module implements a client interface to the POP3 protocol, enabling
626
+ a perl5 application to talk to POP3 servers. This documentation assumes
627
+ that you are familiar with the POP3 protocol described in RFC1939.
628
+ With L<IO::Socket::SSL> installed it also provides support for implicit and
629
+ explicit TLS encryption, i.e. POP3S or POP3+STARTTLS.
630
+
631
+ A new Net::POP3 object must be created with the I<new> method. Once
632
+ this has been done, all POP3 commands are accessed via method calls
633
+ on the object.
634
+
635
+ The Net::POP3 class is a subclass of Net::Cmd and (depending on avaibility) of
636
+ IO::Socket::IP, IO::Socket::INET6 or IO::Socket::INET.
637
+
638
+ =head2 Class Methods
639
+
640
+ =over 4
641
+
642
+ =item C<new([$host][, %options])>
643
+
644
+ This is the constructor for a new Net::POP3 object. C<$host> is the
645
+ name of the remote host to which an POP3 connection is required.
646
+
647
+ C<$host> is optional. If C<$host> is not given then it may instead be
648
+ passed as the C<Host> option described below. If neither is given then
649
+ the C<POP3_Hosts> specified in C<Net::Config> will be used.
650
+
651
+ C<%options> are passed in a hash like fashion, using key and value pairs.
652
+ Possible options are:
653
+
654
+ B<Host> - POP3 host to connect to. It may be a single scalar, as defined for
655
+ the C<PeerAddr> option in L<IO::Socket::INET>, or a reference to
656
+ an array with hosts to try in turn. The L</host> method will return the value
657
+ which was used to connect to the host.
658
+
659
+ B<Port> - port to connect to.
660
+ Default - 110 for plain POP3 and 995 for POP3s (direct SSL).
661
+
662
+ B<SSL> - If the connection should be done from start with SSL, contrary to later
663
+ upgrade with C<starttls>.
664
+ You can use SSL arguments as documented in L<IO::Socket::SSL>, but it will
665
+ usually use the right arguments already.
666
+
667
+ B<LocalAddr> and B<LocalPort> - These parameters are passed directly
668
+ to IO::Socket to allow binding the socket to a specific local address and port.
669
+ For compatibility with older versions B<ResvPort> can be used instead of
670
+ B<LocalPort>.
671
+
672
+ B<Domain> - This parameter is passed directly to IO::Socket and makes it
673
+ possible to enforce IPv4 connections even if L<IO::Socket::IP> is used as super
674
+ class. Alternatively B<Family> can be used.
675
+
676
+ B<Timeout> - Maximum time, in seconds, to wait for a response from the
677
+ POP3 server (default: 120)
678
+
679
+ B<Debug> - Enable debugging information
680
+
681
+ =back
682
+
683
+ =head2 Object Methods
684
+
685
+ Unless otherwise stated all methods return either a I<true> or I<false>
686
+ value, with I<true> meaning that the operation was a success. When a method
687
+ states that it returns a value, failure will be returned as I<undef> or an
688
+ empty list.
689
+
690
+ C<Net::POP3> inherits from C<Net::Cmd> so methods defined in C<Net::Cmd> may
691
+ be used to send commands to the remote POP3 server in addition to the methods
692
+ documented here.
693
+
694
+ =over 4
695
+
696
+ =item C<host()>
697
+
698
+ Returns the value used by the constructor, and passed to IO::Socket::INET,
699
+ to connect to the host.
700
+
701
+ =item C<auth($username, $password)>
702
+
703
+ Attempt SASL authentication.
704
+
705
+ =item C<user($user)>
706
+
707
+ Send the USER command.
708
+
709
+ =item C<pass($pass)>
710
+
711
+ Send the PASS command. Returns the number of messages in the mailbox.
712
+
713
+ =item C<login([$user[, $pass]])>
714
+
715
+ Send both the USER and PASS commands. If C<$pass> is not given the
716
+ C<Net::POP3> uses C<Net::Netrc> to lookup the password using the host
717
+ and username. If the username is not specified then the current user name
718
+ will be used.
719
+
720
+ Returns the number of messages in the mailbox. However if there are no
721
+ messages on the server the string C<"0E0"> will be returned. This is
722
+ will give a true value in a boolean context, but zero in a numeric context.
723
+
724
+ If there was an error authenticating the user then I<undef> will be returned.
725
+
726
+ =item C<starttls(%sslargs)>
727
+
728
+ Upgrade existing plain connection to SSL.
729
+ You can use SSL arguments as documented in L<IO::Socket::SSL>, but it will
730
+ usually use the right arguments already.
731
+
732
+ =item C<apop([$user[, $pass]])>
733
+
734
+ Authenticate with the server identifying as C<$user> with password C<$pass>.
735
+ Similar to L</login>, but the password is not sent in clear text.
736
+
737
+ To use this method you must have the Digest::MD5 or the MD5 module installed,
738
+ otherwise this method will return I<undef>.
739
+
740
+ =item C<banner()>
741
+
742
+ Return the sever's connection banner
743
+
744
+ =item C<capa()>
745
+
746
+ Return a reference to a hash of the capabilities of the server. APOP
747
+ is added as a pseudo capability. Note that I've been unable to
748
+ find a list of the standard capability values, and some appear to
749
+ be multi-word and some are not. We make an attempt at intelligently
750
+ parsing them, but it may not be correct.
751
+
752
+ =item C<capabilities()>
753
+
754
+ Just like capa, but only uses a cache from the last time we asked
755
+ the server, so as to avoid asking more than once.
756
+
757
+ =item C<top($msgnum[, $numlines])>
758
+
759
+ Get the header and the first C<$numlines> of the body for the message
760
+ C<$msgnum>. Returns a reference to an array which contains the lines of text
761
+ read from the server.
762
+
763
+ =item C<list([$msgnum])>
764
+
765
+ If called with an argument the C<list> returns the size of the message
766
+ in octets.
767
+
768
+ If called without arguments a reference to a hash is returned. The
769
+ keys will be the C<$msgnum>'s of all undeleted messages and the values will
770
+ be their size in octets.
771
+
772
+ =item C<get($msgnum[, $fh])>
773
+
774
+ Get the message C<$msgnum> from the remote mailbox. If C<$fh> is not given
775
+ then get returns a reference to an array which contains the lines of
776
+ text read from the server. If C<$fh> is given then the lines returned
777
+ from the server are printed to the filehandle C<$fh>.
778
+
779
+ =item C<getfh($msgnum)>
780
+
781
+ As per get(), but returns a tied filehandle. Reading from this
782
+ filehandle returns the requested message. The filehandle will return
783
+ EOF at the end of the message and should not be reused.
784
+
785
+ =item C<last()>
786
+
787
+ Returns the highest C<$msgnum> of all the messages accessed.
788
+
789
+ =item C<popstat()>
790
+
791
+ Returns a list of two elements. These are the number of undeleted
792
+ elements and the size of the mbox in octets.
793
+
794
+ =item C<ping($user)>
795
+
796
+ Returns a list of two elements. These are the number of new messages
797
+ and the total number of messages for C<$user>.
798
+
799
+ =item C<uidl([$msgnum])>
800
+
801
+ Returns a unique identifier for C<$msgnum> if given. If C<$msgnum> is not
802
+ given C<uidl> returns a reference to a hash where the keys are the
803
+ message numbers and the values are the unique identifiers.
804
+
805
+ =item C<delete($msgnum)>
806
+
807
+ Mark message C<$msgnum> to be deleted from the remote mailbox. All messages
808
+ that are marked to be deleted will be removed from the remote mailbox
809
+ when the server connection closed.
810
+
811
+ =item C<reset()>
812
+
813
+ Reset the status of the remote POP3 server. This includes resetting the
814
+ status of all messages to not be deleted.
815
+
816
+ =item C<quit()>
817
+
818
+ Quit and close the connection to the remote POP3 server. Any messages marked
819
+ as deleted will be deleted from the remote mailbox.
820
+
821
+ =item C<can_inet6()>
822
+
823
+ Returns whether we can use IPv6.
824
+
825
+ =item C<can_ssl()>
826
+
827
+ Returns whether we can use SSL.
828
+
829
+ =back
830
+
831
+ =head2 Notes
832
+
833
+ If a C<Net::POP3> object goes out of scope before C<quit> method is called
834
+ then the C<reset> method will called before the connection is closed. This
835
+ means that any messages marked to be deleted will not be.
836
+
837
+ =head1 EXPORTS
838
+
839
+ I<None>.
840
+
841
+ =head1 KNOWN BUGS
842
+
843
+ See L<https://rt.cpan.org/Dist/Display.html?Status=Active&Queue=libnet>.
844
+
845
+ =head1 SEE ALSO
846
+
847
+ L<Net::Netrc>,
848
+ L<Net::Cmd>,
849
+ L<IO::Socket::SSL>.
850
+
851
+ =head1 AUTHOR
852
+
853
+ Graham Barr E<lt>L<gbarr@pobox.com|mailto:gbarr@pobox.com>E<gt>.
854
+
855
+ Steve Hay E<lt>L<shay@cpan.org|mailto:shay@cpan.org>E<gt> is now maintaining
856
+ libnet as of version 1.22_02.
857
+
858
+ =head1 COPYRIGHT
859
+
860
+ Copyright (C) 1995-2004 Graham Barr. All rights reserved.
861
+
862
+ Copyright (C) 2013-2016, 2020 Steve Hay. All rights reserved.
863
+
864
+ =head1 LICENCE
865
+
866
+ This module is free software; you can redistribute it and/or modify it under the
867
+ same terms as Perl itself, i.e. under the terms of either the GNU General Public
868
+ License or the Artistic License, as specified in the F<LICENCE> file.
869
+
870
+ =head1 VERSION
871
+
872
+ Version 3.15
873
+
874
+ =head1 DATE
875
+
876
+ 20 March 2023
877
+
878
+ =head1 HISTORY
879
+
880
+ See the F<Changes> file.
881
+
882
+ =cut
git/usr/share/perl5/core_perl/Net/Ping.pm ADDED
@@ -0,0 +1,2589 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package Net::Ping;
2
+
3
+ require 5.002;
4
+ require Exporter;
5
+
6
+ use strict;
7
+ use vars qw(@ISA @EXPORT @EXPORT_OK $VERSION
8
+ $def_timeout $def_proto $def_factor $def_family
9
+ $max_datasize $pingstring $hires $source_verify $syn_forking);
10
+ use Fcntl qw( F_GETFL F_SETFL O_NONBLOCK );
11
+ use Socket 2.007;
12
+ use Socket qw( SOCK_DGRAM SOCK_STREAM SOCK_RAW AF_INET PF_INET IPPROTO_TCP
13
+ SOL_SOCKET SO_ERROR SO_BROADCAST
14
+ IPPROTO_IP IP_TOS IP_TTL
15
+ inet_ntoa inet_aton getnameinfo sockaddr_in );
16
+ use POSIX qw( ENOTCONN ECONNREFUSED ECONNRESET EINPROGRESS EWOULDBLOCK EAGAIN
17
+ WNOHANG );
18
+ use FileHandle;
19
+ use Carp;
20
+ use Time::HiRes;
21
+
22
+ @ISA = qw(Exporter);
23
+ @EXPORT = qw(pingecho);
24
+ @EXPORT_OK = qw(wakeonlan);
25
+ $VERSION = "2.76";
26
+
27
+ # Globals
28
+
29
+ $def_timeout = 5; # Default timeout to wait for a reply
30
+ $def_proto = "tcp"; # Default protocol to use for pinging
31
+ $def_factor = 1.2; # Default exponential backoff rate.
32
+ $def_family = AF_INET; # Default family.
33
+ $max_datasize = 65535; # Maximum data bytes. recommended: 1472 (Ethernet MTU: 1500)
34
+ # The data we exchange with the server for the stream protocol
35
+ $pingstring = "pingschwingping!\n";
36
+ $source_verify = 1; # Default is to verify source endpoint
37
+ $syn_forking = 0;
38
+
39
+ # Constants
40
+
41
+ my $AF_INET6 = eval { Socket::AF_INET6() } || 30;
42
+ my $AF_UNSPEC = eval { Socket::AF_UNSPEC() };
43
+ my $AI_NUMERICHOST = eval { Socket::AI_NUMERICHOST() } || 4;
44
+ my $NI_NUMERICHOST = eval { Socket::NI_NUMERICHOST() } || 2;
45
+ my $IPPROTO_IPV6 = eval { Socket::IPPROTO_IPV6() } || 41;
46
+ my $NIx_NOSERV = eval { Socket::NIx_NOSERV() } || 2;
47
+ #my $IPV6_HOPLIMIT = eval { Socket::IPV6_HOPLIMIT() }; # ping6 -h 0-255
48
+ my $qr_family = qr/^(?:(?:(:?ip)?v?(?:4|6))|${\AF_INET}|$AF_INET6)$/;
49
+ my $qr_family4 = qr/^(?:(?:(:?ip)?v?4)|${\AF_INET})$/;
50
+ my $Socket_VERSION = eval $Socket::VERSION;
51
+
52
+ if ($^O =~ /Win32/i) {
53
+ # Hack to avoid this Win32 spewage:
54
+ # Your vendor has not defined POSIX macro ECONNREFUSED
55
+ my @pairs = (ECONNREFUSED => 10061, # "Unknown Error" Special Win32 Response?
56
+ ENOTCONN => 10057,
57
+ ECONNRESET => 10054,
58
+ EINPROGRESS => 10036,
59
+ EWOULDBLOCK => 10035,
60
+ );
61
+ while (my $name = shift @pairs) {
62
+ my $value = shift @pairs;
63
+ # When defined, these all are non-zero
64
+ unless (eval $name) {
65
+ no strict 'refs';
66
+ *{$name} = defined prototype \&{$name} ? sub () {$value} : sub {$value};
67
+ }
68
+ }
69
+ # $syn_forking = 1; # XXX possibly useful in < Win2K ?
70
+ };
71
+
72
+ # Description: The pingecho() subroutine is provided for backward
73
+ # compatibility with the original Net::Ping. It accepts a host
74
+ # name/IP and an optional timeout in seconds. Create a tcp ping
75
+ # object and try pinging the host. The result of the ping is returned.
76
+
77
+ sub pingecho
78
+ {
79
+ my ($host, # Name or IP number of host to ping
80
+ $timeout # Optional timeout in seconds
81
+ ) = @_;
82
+ my ($p); # A ping object
83
+
84
+ $p = Net::Ping->new("tcp", $timeout);
85
+ $p->ping($host); # Going out of scope closes the connection
86
+ }
87
+
88
+ # Description: The new() method creates a new ping object. Optional
89
+ # parameters may be specified for the protocol to use, the timeout in
90
+ # seconds and the size in bytes of additional data which should be
91
+ # included in the packet.
92
+ # After the optional parameters are checked, the data is constructed
93
+ # and a socket is opened if appropriate. The object is returned.
94
+
95
+ sub new
96
+ {
97
+ my ($this,
98
+ $proto, # Optional protocol to use for pinging
99
+ $timeout, # Optional timeout in seconds
100
+ $data_size, # Optional additional bytes of data
101
+ $device, # Optional device to use
102
+ $tos, # Optional ToS to set
103
+ $ttl, # Optional TTL to set
104
+ $family, # Optional address family (AF_INET)
105
+ ) = @_;
106
+ my $class = ref($this) || $this;
107
+ my $self = {};
108
+ my ($cnt, # Count through data bytes
109
+ $min_datasize # Minimum data bytes required
110
+ );
111
+
112
+ bless($self, $class);
113
+ if (ref $proto eq 'HASH') { # support named args
114
+ for my $k (qw(proto timeout data_size device tos ttl family
115
+ gateway host port bind retrans pingstring source_verify
116
+ econnrefused dontfrag
117
+ IPV6_USE_MIN_MTU IPV6_RECVPATHMTU IPV6_HOPLIMIT))
118
+ {
119
+ if (exists $proto->{$k}) {
120
+ $self->{$k} = $proto->{$k};
121
+ # some are still globals
122
+ if ($k eq 'pingstring') { $pingstring = $proto->{$k} }
123
+ if ($k eq 'source_verify') { $source_verify = $proto->{$k} }
124
+ # and some are local
125
+ $timeout = $proto->{$k} if ($k eq 'timeout');
126
+ $data_size = $proto->{$k} if ($k eq 'data_size');
127
+ $device = $proto->{$k} if ($k eq 'device');
128
+ $tos = $proto->{$k} if ($k eq 'tos');
129
+ $ttl = $proto->{$k} if ($k eq 'ttl');
130
+ $family = $proto->{$k} if ($k eq 'family');
131
+ delete $proto->{$k};
132
+ }
133
+ }
134
+ if (%$proto) {
135
+ croak("Invalid named argument: ",join(" ",keys (%$proto)));
136
+ }
137
+ $proto = $self->{'proto'};
138
+ }
139
+
140
+ $proto = $def_proto unless $proto; # Determine the protocol
141
+ croak('Protocol for ping must be "icmp", "icmpv6", "udp", "tcp", "syn", "stream" or "external"')
142
+ unless $proto =~ m/^(icmp|icmpv6|udp|tcp|syn|stream|external)$/;
143
+ $self->{proto} = $proto;
144
+
145
+ $timeout = $def_timeout unless defined $timeout; # Determine the timeout
146
+ croak("Default timeout for ping must be greater than 0 seconds")
147
+ if $timeout <= 0;
148
+ $self->{timeout} = $timeout;
149
+
150
+ $self->{device} = $device;
151
+
152
+ $self->{tos} = $tos;
153
+
154
+ if ($self->{'host'}) {
155
+ my $host = $self->{'host'};
156
+ my $ip = $self->_resolv($host) or
157
+ carp("could not resolve host $host");
158
+ $self->{host} = $ip;
159
+ $self->{family} = $ip->{family};
160
+ }
161
+
162
+ if ($self->{bind}) {
163
+ my $addr = $self->{bind};
164
+ my $ip = $self->_resolv($addr)
165
+ or carp("could not resolve local addr $addr");
166
+ $self->{local_addr} = $ip;
167
+ } else {
168
+ $self->{local_addr} = undef; # Don't bind by default
169
+ }
170
+
171
+ if ($self->{proto} eq 'icmp') {
172
+ croak('TTL must be from 0 to 255')
173
+ if ($ttl && ($ttl < 0 || $ttl > 255));
174
+ $self->{ttl} = $ttl;
175
+ }
176
+
177
+ if ($family) {
178
+ if ($family =~ $qr_family) {
179
+ if ($family =~ $qr_family4) {
180
+ $self->{family} = AF_INET;
181
+ } else {
182
+ $self->{family} = $AF_INET6;
183
+ }
184
+ } else {
185
+ croak('Family must be "ipv4" or "ipv6"')
186
+ }
187
+ } else {
188
+ if ($self->{proto} eq 'icmpv6') {
189
+ $self->{family} = $AF_INET6;
190
+ } else {
191
+ $self->{family} = $def_family;
192
+ }
193
+ }
194
+
195
+ $min_datasize = ($proto eq "udp") ? 1 : 0; # Determine data size
196
+ $data_size = $min_datasize unless defined($data_size) && $proto ne "tcp";
197
+ # allow for fragmented packets if data_size>1472 (MTU 1500)
198
+ croak("Data for ping must be from $min_datasize to $max_datasize bytes")
199
+ if ($data_size < $min_datasize) || ($data_size > $max_datasize);
200
+ $data_size-- if $self->{proto} eq "udp"; # We provide the first byte
201
+ $self->{data_size} = $data_size;
202
+
203
+ $self->{data} = ""; # Construct data bytes
204
+ for ($cnt = 0; $cnt < $self->{data_size}; $cnt++)
205
+ {
206
+ $self->{data} .= chr($cnt % 256);
207
+ }
208
+
209
+ # Default exponential backoff rate
210
+ $self->{retrans} = $def_factor unless exists $self->{retrans};
211
+ # Default Connection refused behavior
212
+ $self->{econnrefused} = undef unless exists $self->{econnrefused};
213
+
214
+ $self->{seq} = 0; # For counting packets
215
+ if ($self->{proto} eq "udp") # Open a socket
216
+ {
217
+ $self->{proto_num} = eval { (getprotobyname('udp'))[2] } ||
218
+ croak("Can't udp protocol by name");
219
+ $self->{port_num} = $self->{port}
220
+ || (getservbyname('echo', 'udp'))[2]
221
+ || croak("Can't get udp echo port by name");
222
+ $self->{fh} = FileHandle->new();
223
+ socket($self->{fh}, PF_INET, SOCK_DGRAM,
224
+ $self->{proto_num}) ||
225
+ croak("udp socket error - $!");
226
+ $self->_setopts();
227
+ }
228
+ elsif ($self->{proto} eq "icmp")
229
+ {
230
+ croak("icmp ping requires root privilege") if !_isroot();
231
+ $self->{proto_num} = eval { (getprotobyname('icmp'))[2] } ||
232
+ croak("Can't get icmp protocol by name");
233
+ $self->{pid} = $$ & 0xffff; # Save lower 16 bits of pid
234
+ $self->{fh} = FileHandle->new();
235
+ socket($self->{fh}, PF_INET, SOCK_RAW, $self->{proto_num}) ||
236
+ croak("icmp socket error - $!");
237
+ $self->_setopts();
238
+ if ($self->{'ttl'}) {
239
+ setsockopt($self->{fh}, IPPROTO_IP, IP_TTL, pack("I*", $self->{'ttl'}))
240
+ or croak "error configuring ttl to $self->{'ttl'} $!";
241
+ }
242
+ }
243
+ elsif ($self->{proto} eq "icmpv6")
244
+ {
245
+ #croak("icmpv6 ping requires root privilege") if !_isroot();
246
+ croak("Wrong family $self->{family} for icmpv6 protocol")
247
+ if $self->{family} and $self->{family} != $AF_INET6;
248
+ $self->{family} = $AF_INET6;
249
+ $self->{proto_num} = eval { (getprotobyname('ipv6-icmp'))[2] } ||
250
+ croak("Can't get ipv6-icmp protocol by name"); # 58
251
+ $self->{pid} = $$ & 0xffff; # Save lower 16 bits of pid
252
+ $self->{fh} = FileHandle->new();
253
+ socket($self->{fh}, $AF_INET6, SOCK_RAW, $self->{proto_num}) ||
254
+ croak("icmp socket error - $!");
255
+ $self->_setopts();
256
+ if ($self->{'gateway'}) {
257
+ my $g = $self->{gateway};
258
+ my $ip = $self->_resolv($g)
259
+ or croak("nonexistent gateway $g");
260
+ $self->{family} eq $AF_INET6
261
+ or croak("gateway requires the AF_INET6 family");
262
+ $ip->{family} eq $AF_INET6
263
+ or croak("gateway address needs to be IPv6");
264
+ my $IPV6_NEXTHOP = eval { Socket::IPV6_NEXTHOP() } || 48; # IPV6_3542NEXTHOP, or 21
265
+ setsockopt($self->{fh}, $IPPROTO_IPV6, $IPV6_NEXTHOP, _pack_sockaddr_in($ip))
266
+ or croak "error configuring gateway to $g NEXTHOP $!";
267
+ }
268
+ if (exists $self->{IPV6_USE_MIN_MTU}) {
269
+ my $IPV6_USE_MIN_MTU = eval { Socket::IPV6_USE_MIN_MTU() } || 42;
270
+ setsockopt($self->{fh}, $IPPROTO_IPV6, $IPV6_USE_MIN_MTU,
271
+ pack("I*", $self->{'IPV6_USE_MIN_MT'}))
272
+ or croak "error configuring IPV6_USE_MIN_MT} $!";
273
+ }
274
+ if (exists $self->{IPV6_RECVPATHMTU}) {
275
+ my $IPV6_RECVPATHMTU = eval { Socket::IPV6_RECVPATHMTU() } || 43;
276
+ setsockopt($self->{fh}, $IPPROTO_IPV6, $IPV6_RECVPATHMTU,
277
+ pack("I*", $self->{'RECVPATHMTU'}))
278
+ or croak "error configuring IPV6_RECVPATHMTU $!";
279
+ }
280
+ if ($self->{'tos'}) {
281
+ my $proto = $self->{family} == AF_INET ? IPPROTO_IP : $IPPROTO_IPV6;
282
+ setsockopt($self->{fh}, $proto, IP_TOS, pack("I*", $self->{'tos'}))
283
+ or croak "error configuring tos to $self->{'tos'} $!";
284
+ }
285
+ if ($self->{'ttl'}) {
286
+ my $proto = $self->{family} == AF_INET ? IPPROTO_IP : $IPPROTO_IPV6;
287
+ setsockopt($self->{fh}, $proto, IP_TTL, pack("I*", $self->{'ttl'}))
288
+ or croak "error configuring ttl to $self->{'ttl'} $!";
289
+ }
290
+ }
291
+ elsif ($self->{proto} eq "tcp" || $self->{proto} eq "stream")
292
+ {
293
+ $self->{proto_num} = eval { (getprotobyname('tcp'))[2] } ||
294
+ croak("Can't get tcp protocol by name");
295
+ $self->{port_num} = $self->{port}
296
+ || (getservbyname('echo', 'tcp'))[2]
297
+ || croak("Can't get tcp echo port by name");
298
+ $self->{fh} = FileHandle->new();
299
+ }
300
+ elsif ($self->{proto} eq "syn")
301
+ {
302
+ $self->{proto_num} = eval { (getprotobyname('tcp'))[2] } ||
303
+ croak("Can't get tcp protocol by name");
304
+ $self->{port_num} = (getservbyname('echo', 'tcp'))[2] ||
305
+ croak("Can't get tcp echo port by name");
306
+ if ($syn_forking) {
307
+ $self->{fork_rd} = FileHandle->new();
308
+ $self->{fork_wr} = FileHandle->new();
309
+ pipe($self->{fork_rd}, $self->{fork_wr});
310
+ $self->{fh} = FileHandle->new();
311
+ $self->{good} = {};
312
+ $self->{bad} = {};
313
+ } else {
314
+ $self->{wbits} = "";
315
+ $self->{bad} = {};
316
+ }
317
+ $self->{syn} = {};
318
+ $self->{stop_time} = 0;
319
+ }
320
+
321
+ return($self);
322
+ }
323
+
324
+ # Description: Set the local IP address from which pings will be sent.
325
+ # For ICMP, UDP and TCP pings, just saves the address to be used when
326
+ # the socket is opened. Returns non-zero if successful; croaks on error.
327
+ sub bind
328
+ {
329
+ my ($self,
330
+ $local_addr # Name or IP number of local interface
331
+ ) = @_;
332
+ my ($ip, # Hash of addr (string), addr_in (packed), family
333
+ $h # resolved hash
334
+ );
335
+
336
+ croak("Usage: \$p->bind(\$local_addr)") unless @_ == 2;
337
+ croak("already bound") if defined($self->{local_addr}) &&
338
+ ($self->{proto} eq "udp" || $self->{proto} eq "icmp");
339
+
340
+ $ip = $self->_resolv($local_addr);
341
+ carp("nonexistent local address $local_addr") unless defined($ip);
342
+ $self->{local_addr} = $ip;
343
+
344
+ if (($self->{proto} ne "udp") &&
345
+ ($self->{proto} ne "icmp") &&
346
+ ($self->{proto} ne "tcp") &&
347
+ ($self->{proto} ne "syn"))
348
+ {
349
+ croak("Unknown protocol \"$self->{proto}\" in bind()");
350
+ }
351
+
352
+ return 1;
353
+ }
354
+
355
+ # Description: A select() wrapper that compensates for platform
356
+ # peculiarities.
357
+ sub mselect
358
+ {
359
+ if ($_[3] > 0 and $^O eq 'MSWin32') {
360
+ # On windows, select() doesn't process the message loop,
361
+ # but sleep() will, allowing alarm() to interrupt the latter.
362
+ # So we chop up the timeout into smaller pieces and interleave
363
+ # select() and sleep() calls.
364
+ my $t = $_[3];
365
+ my $gran = 0.5; # polling granularity in seconds
366
+ my @args = @_;
367
+ while (1) {
368
+ $gran = $t if $gran > $t;
369
+ my $nfound = select($_[0], $_[1], $_[2], $gran);
370
+ undef $nfound if $nfound == -1;
371
+ $t -= $gran;
372
+ return $nfound if $nfound or !defined($nfound) or $t <= 0;
373
+
374
+ sleep(0);
375
+ ($_[0], $_[1], $_[2]) = @args;
376
+ }
377
+ }
378
+ else {
379
+ my $nfound = select($_[0], $_[1], $_[2], $_[3]);
380
+ undef $nfound if $nfound == -1;
381
+ return $nfound;
382
+ }
383
+ }
384
+
385
+ # Description: Allow UDP source endpoint comparison to be
386
+ # skipped for those remote interfaces that do
387
+ # not response from the same endpoint.
388
+
389
+ sub source_verify
390
+ {
391
+ my $self = shift;
392
+ $source_verify = 1 unless defined
393
+ ($source_verify = ((defined $self) && (ref $self)) ? shift() : $self);
394
+ }
395
+
396
+ # Description: Set whether or not the connect
397
+ # behavior should enforce remote service
398
+ # availability as well as reachability.
399
+
400
+ sub service_check
401
+ {
402
+ my $self = shift;
403
+ $self->{econnrefused} = 1 unless defined
404
+ ($self->{econnrefused} = shift());
405
+ }
406
+
407
+ sub tcp_service_check
408
+ {
409
+ service_check(@_);
410
+ }
411
+
412
+ # Description: Set exponential backoff for retransmission.
413
+ # Should be > 1 to retain exponential properties.
414
+ # If set to 0, retransmissions are disabled.
415
+
416
+ sub retrans
417
+ {
418
+ my $self = shift;
419
+ $self->{retrans} = shift;
420
+ }
421
+
422
+ sub _IsAdminUser {
423
+ return unless $^O eq 'MSWin32' or $^O eq "cygwin";
424
+ return unless eval { require Win32 };
425
+ return unless defined &Win32::IsAdminUser;
426
+ return Win32::IsAdminUser();
427
+ }
428
+
429
+ sub _isroot {
430
+ if (($> and $^O ne 'VMS' and $^O ne 'cygwin')
431
+ or (($^O eq 'MSWin32' or $^O eq 'cygwin')
432
+ and !_IsAdminUser())
433
+ or ($^O eq 'VMS'
434
+ and (`write sys\$output f\$privilege("SYSPRV")` =~ m/FALSE/))) {
435
+ return 0;
436
+ }
437
+ else {
438
+ return 1;
439
+ }
440
+ }
441
+
442
+ # Description: Sets ipv6 reachability
443
+ # REACHCONF was removed in RFC3542, ping6 -R supports it. requires root.
444
+
445
+ sub IPV6_REACHCONF
446
+ {
447
+ my $self = shift;
448
+ my $on = shift;
449
+ if ($on) {
450
+ my $reachconf = eval { Socket::IPV6_REACHCONF() };
451
+ if (!$reachconf) {
452
+ carp "IPV6_REACHCONF not supported on this platform";
453
+ return 0;
454
+ }
455
+ if (!_isroot()) {
456
+ carp "IPV6_REACHCONF requires root permissions";
457
+ return 0;
458
+ }
459
+ $self->{IPV6_REACHCONF} = 1;
460
+ }
461
+ else {
462
+ return $self->{IPV6_REACHCONF};
463
+ }
464
+ }
465
+
466
+ # Description: set it on or off.
467
+
468
+ sub IPV6_USE_MIN_MTU
469
+ {
470
+ my $self = shift;
471
+ my $on = shift;
472
+ if (defined $on) {
473
+ my $IPV6_USE_MIN_MTU = eval { Socket::IPV6_USE_MIN_MTU() } || 43;
474
+ #if (!$IPV6_USE_MIN_MTU) {
475
+ # carp "IPV6_USE_MIN_MTU not supported on this platform";
476
+ # return 0;
477
+ #}
478
+ $self->{IPV6_USE_MIN_MTU} = $on ? 1 : 0;
479
+ setsockopt($self->{fh}, $IPPROTO_IPV6, $IPV6_USE_MIN_MTU,
480
+ pack("I*", $self->{'IPV6_USE_MIN_MT'}))
481
+ or croak "error configuring IPV6_USE_MIN_MT} $!";
482
+ }
483
+ else {
484
+ return $self->{IPV6_USE_MIN_MTU};
485
+ }
486
+ }
487
+
488
+ # Description: notify an according MTU
489
+
490
+ sub IPV6_RECVPATHMTU
491
+ {
492
+ my $self = shift;
493
+ my $on = shift;
494
+ if ($on) {
495
+ my $IPV6_RECVPATHMTU = eval { Socket::IPV6_RECVPATHMTU() } || 43;
496
+ #if (!$RECVPATHMTU) {
497
+ # carp "IPV6_RECVPATHMTU not supported on this platform";
498
+ # return 0;
499
+ #}
500
+ $self->{IPV6_RECVPATHMTU} = 1;
501
+ setsockopt($self->{fh}, $IPPROTO_IPV6, $IPV6_RECVPATHMTU,
502
+ pack("I*", $self->{'IPV6_RECVPATHMTU'}))
503
+ or croak "error configuring IPV6_RECVPATHMTU} $!";
504
+ }
505
+ else {
506
+ return $self->{IPV6_RECVPATHMTU};
507
+ }
508
+ }
509
+
510
+ # Description: allows the module to use milliseconds as returned by
511
+ # the Time::HiRes module
512
+
513
+ $hires = 1;
514
+ sub hires
515
+ {
516
+ my $self = shift;
517
+ $hires = 1 unless defined
518
+ ($hires = ((defined $self) && (ref $self)) ? shift() : $self);
519
+ }
520
+
521
+ sub time
522
+ {
523
+ return $hires ? Time::HiRes::time() : CORE::time();
524
+ }
525
+
526
+ # Description: Sets or clears the O_NONBLOCK flag on a file handle.
527
+ sub socket_blocking_mode
528
+ {
529
+ my ($self,
530
+ $fh, # the file handle whose flags are to be modified
531
+ $block) = @_; # if true then set the blocking
532
+ # mode (clear O_NONBLOCK), otherwise
533
+ # set the non-blocking mode (set O_NONBLOCK)
534
+
535
+ my $flags;
536
+ if ($^O eq 'MSWin32' || $^O eq 'VMS') {
537
+ # FIONBIO enables non-blocking sockets on windows and vms.
538
+ # FIONBIO is (0x80000000|(4<<16)|(ord('f')<<8)|126), as per winsock.h, ioctl.h
539
+ my $f = 0x8004667e;
540
+ my $v = pack("L", $block ? 0 : 1);
541
+ ioctl($fh, $f, $v) or croak("ioctl failed: $!");
542
+ return;
543
+ }
544
+ if ($flags = fcntl($fh, F_GETFL, 0)) {
545
+ $flags = $block ? ($flags & ~O_NONBLOCK) : ($flags | O_NONBLOCK);
546
+ if (!fcntl($fh, F_SETFL, $flags)) {
547
+ croak("fcntl F_SETFL: $!");
548
+ }
549
+ } else {
550
+ croak("fcntl F_GETFL: $!");
551
+ }
552
+ }
553
+
554
+ # Description: Ping a host name or IP number with an optional timeout.
555
+ # First lookup the host, and return undef if it is not found. Otherwise
556
+ # perform the specific ping method based on the protocol. Return the
557
+ # result of the ping.
558
+
559
+ sub ping
560
+ {
561
+ my ($self,
562
+ $host, # Name or IP number of host to ping
563
+ $timeout, # Seconds after which ping times out
564
+ $family, # Address family
565
+ ) = @_;
566
+ my ($ip, # Hash of addr (string), addr_in (packed), family
567
+ $ret, # The return value
568
+ $ping_time, # When ping began
569
+ );
570
+
571
+ $host = $self->{host} if !defined $host and $self->{host};
572
+ croak("Usage: \$p->ping([ \$host [, \$timeout [, \$family]]])") if @_ > 4 or !$host;
573
+ $timeout = $self->{timeout} unless $timeout;
574
+ croak("Timeout must be greater than 0 seconds") if $timeout <= 0;
575
+
576
+ if ($family) {
577
+ if ($family =~ $qr_family) {
578
+ if ($family =~ $qr_family4) {
579
+ $self->{family_local} = AF_INET;
580
+ } else {
581
+ $self->{family_local} = $AF_INET6;
582
+ }
583
+ } else {
584
+ croak('Family must be "ipv4" or "ipv6"')
585
+ }
586
+ } else {
587
+ $self->{family_local} = $self->{family};
588
+ }
589
+
590
+ $ip = $self->_resolv($host);
591
+ return () unless defined($ip); # Does host exist?
592
+
593
+ # Dispatch to the appropriate routine.
594
+ $ping_time = &time();
595
+ if ($self->{proto} eq "external") {
596
+ $ret = $self->ping_external($ip, $timeout);
597
+ }
598
+ elsif ($self->{proto} eq "udp") {
599
+ $ret = $self->ping_udp($ip, $timeout);
600
+ }
601
+ elsif ($self->{proto} eq "icmp") {
602
+ $ret = $self->ping_icmp($ip, $timeout);
603
+ }
604
+ elsif ($self->{proto} eq "icmpv6") {
605
+ $ret = $self->ping_icmpv6($ip, $timeout);
606
+ }
607
+ elsif ($self->{proto} eq "tcp") {
608
+ $ret = $self->ping_tcp($ip, $timeout);
609
+ }
610
+ elsif ($self->{proto} eq "stream") {
611
+ $ret = $self->ping_stream($ip, $timeout);
612
+ }
613
+ elsif ($self->{proto} eq "syn") {
614
+ $ret = $self->ping_syn($host, $ip, $ping_time, $ping_time+$timeout);
615
+ } else {
616
+ croak("Unknown protocol \"$self->{proto}\" in ping()");
617
+ }
618
+
619
+ return wantarray ? ($ret, &time() - $ping_time, $self->ntop($ip)) : $ret;
620
+ }
621
+
622
+ # Uses Net::Ping::External to do an external ping.
623
+ sub ping_external {
624
+ my ($self,
625
+ $ip, # Hash of addr (string), addr_in (packed), family
626
+ $timeout, # Seconds after which ping times out
627
+ $family
628
+ ) = @_;
629
+
630
+ $ip = $self->{host} if !defined $ip and $self->{host};
631
+ $timeout = $self->{timeout} if !defined $timeout and $self->{timeout};
632
+ my @addr = exists $ip->{addr_in}
633
+ ? ('ip' => $ip->{addr_in})
634
+ : ('host' => $ip->{host});
635
+
636
+ eval {
637
+ local @INC = @INC;
638
+ pop @INC if $INC[-1] eq '.';
639
+ require Net::Ping::External;
640
+ } or croak('Protocol "external" not supported on your system: Net::Ping::External not found');
641
+ return Net::Ping::External::ping(@addr, timeout => $timeout,
642
+ family => $family);
643
+ }
644
+
645
+ # h2ph "asm/socket.h"
646
+ # require "asm/socket.ph";
647
+ use constant SO_BINDTODEVICE => 25;
648
+ use constant ICMP_ECHOREPLY => 0; # ICMP packet types
649
+ use constant ICMPv6_ECHOREPLY => 129; # ICMP packet types
650
+ use constant ICMP_UNREACHABLE => 3; # ICMP packet types
651
+ use constant ICMPv6_UNREACHABLE => 1; # ICMP packet types
652
+ use constant ICMPv6_NI_REPLY => 140; # ICMP packet types
653
+ use constant ICMP_ECHO => 8;
654
+ use constant ICMPv6_ECHO => 128;
655
+ use constant ICMP_TIME_EXCEEDED => 11; # ICMP packet types
656
+ use constant ICMP_PARAMETER_PROBLEM => 12; # ICMP packet types
657
+ use constant ICMP_TIMESTAMP => 13;
658
+ use constant ICMP_TIMESTAMP_REPLY => 14;
659
+ use constant ICMP_STRUCT => "C2 n3 A"; # Structure of a minimal ICMP packet
660
+ use constant ICMP_TIMESTAMP_STRUCT => "C2 n3 N3"; # Structure of a minimal timestamp ICMP packet
661
+ use constant SUBCODE => 0; # No ICMP subcode for ECHO and ECHOREPLY
662
+ use constant ICMP_FLAGS => 0; # No special flags for send or recv
663
+ use constant ICMP_PORT => 0; # No port with ICMP
664
+ use constant IP_MTU_DISCOVER => 10; # linux only
665
+
666
+ sub message_type
667
+ {
668
+ my ($self,
669
+ $type
670
+ ) = @_;
671
+
672
+ croak "Setting message type only supported on 'icmp' protocol"
673
+ unless $self->{proto} eq 'icmp';
674
+
675
+ return $self->{message_type} || 'echo'
676
+ unless defined($type);
677
+
678
+ croak "Supported icmp message type are limited to 'echo' and 'timestamp': '$type' not supported"
679
+ unless $type =~ /^echo|timestamp$/i;
680
+
681
+ $self->{message_type} = lc($type);
682
+ }
683
+
684
+ sub ping_icmp
685
+ {
686
+ my ($self,
687
+ $ip, # Hash of addr (string), addr_in (packed), family
688
+ $timeout # Seconds after which ping times out
689
+ ) = @_;
690
+
691
+ my ($saddr, # sockaddr_in with port and ip
692
+ $checksum, # Checksum of ICMP packet
693
+ $msg, # ICMP packet to send
694
+ $len_msg, # Length of $msg
695
+ $rbits, # Read bits, filehandles for reading
696
+ $nfound, # Number of ready filehandles found
697
+ $finish_time, # Time ping should be finished
698
+ $done, # set to 1 when we are done
699
+ $ret, # Return value
700
+ $recv_msg, # Received message including IP header
701
+ $recv_msg_len, # Length of recevied message, less any additional data
702
+ $from_saddr, # sockaddr_in of sender
703
+ $from_port, # Port packet was sent from
704
+ $from_ip, # Packed IP of sender
705
+ $timestamp_msg, # ICMP timestamp message type
706
+ $from_type, # ICMP type
707
+ $from_subcode, # ICMP subcode
708
+ $from_chk, # ICMP packet checksum
709
+ $from_pid, # ICMP packet id
710
+ $from_seq, # ICMP packet sequence
711
+ $from_msg # ICMP message
712
+ );
713
+
714
+ $ip = $self->{host} if !defined $ip and $self->{host};
715
+ $timeout = $self->{timeout} if !defined $timeout and $self->{timeout};
716
+ $timestamp_msg = $self->{message_type} && $self->{message_type} eq 'timestamp' ? 1 : 0;
717
+
718
+ socket($self->{fh}, $ip->{family}, SOCK_RAW, $self->{proto_num}) ||
719
+ croak("icmp socket error - $!");
720
+
721
+ if (defined $self->{local_addr} &&
722
+ !CORE::bind($self->{fh}, _pack_sockaddr_in(0, $self->{local_addr}))) {
723
+ croak("icmp bind error - $!");
724
+ }
725
+ $self->_setopts();
726
+
727
+ $self->{seq} = ($self->{seq} + 1) % 65536; # Increment sequence
728
+ $checksum = 0; # No checksum for starters
729
+ if ($ip->{family} == AF_INET) {
730
+ if ($timestamp_msg) {
731
+ $msg = pack(ICMP_TIMESTAMP_STRUCT, ICMP_TIMESTAMP, SUBCODE,
732
+ $checksum, $self->{pid}, $self->{seq}, 0, 0, 0);
733
+ } else {
734
+ $msg = pack(ICMP_STRUCT . $self->{data_size}, ICMP_ECHO, SUBCODE,
735
+ $checksum, $self->{pid}, $self->{seq}, $self->{data});
736
+ }
737
+ } else {
738
+ # how to get SRC
739
+ my $pseudo_header = pack('a16a16Nnn', $ip->{addr_in}, $ip->{addr_in}, 8+length($self->{data}), 0, 0x003a);
740
+ $msg = pack(ICMP_STRUCT . $self->{data_size}, ICMPv6_ECHO, SUBCODE,
741
+ $checksum, $self->{pid}, $self->{seq}, $self->{data});
742
+ $msg = $pseudo_header.$msg
743
+ }
744
+ $checksum = Net::Ping->checksum($msg);
745
+ if ($ip->{family} == AF_INET) {
746
+ if ($timestamp_msg) {
747
+ $msg = pack(ICMP_TIMESTAMP_STRUCT, ICMP_TIMESTAMP, SUBCODE,
748
+ $checksum, $self->{pid}, $self->{seq}, 0, 0, 0);
749
+ } else {
750
+ $msg = pack(ICMP_STRUCT . $self->{data_size}, ICMP_ECHO, SUBCODE,
751
+ $checksum, $self->{pid}, $self->{seq}, $self->{data});
752
+ }
753
+ } else {
754
+ $msg = pack(ICMP_STRUCT . $self->{data_size}, ICMPv6_ECHO, SUBCODE,
755
+ $checksum, $self->{pid}, $self->{seq}, $self->{data});
756
+ }
757
+ $len_msg = length($msg);
758
+ $saddr = _pack_sockaddr_in(ICMP_PORT, $ip);
759
+ $self->{from_ip} = undef;
760
+ $self->{from_type} = undef;
761
+ $self->{from_subcode} = undef;
762
+ send($self->{fh}, $msg, ICMP_FLAGS, $saddr); # Send the message
763
+
764
+ $rbits = "";
765
+ vec($rbits, $self->{fh}->fileno(), 1) = 1;
766
+ $ret = 0;
767
+ $done = 0;
768
+ $finish_time = &time() + $timeout; # Must be done by this time
769
+ while (!$done && $timeout > 0) # Keep trying if we have time
770
+ {
771
+ $nfound = mselect((my $rout=$rbits), undef, undef, $timeout); # Wait for packet
772
+ $timeout = $finish_time - &time(); # Get remaining time
773
+ if (!defined($nfound)) # Hmm, a strange error
774
+ {
775
+ $ret = undef;
776
+ $done = 1;
777
+ }
778
+ elsif ($nfound) # Got a packet from somewhere
779
+ {
780
+ $recv_msg = "";
781
+ $from_pid = -1;
782
+ $from_seq = -1;
783
+ $from_saddr = recv($self->{fh}, $recv_msg, 1500, ICMP_FLAGS);
784
+ $recv_msg_len = length($recv_msg) - length($self->{data});
785
+ ($from_port, $from_ip) = _unpack_sockaddr_in($from_saddr, $ip->{family});
786
+ # ICMP echo includes the header and ICMPv6 doesn't.
787
+ # IPv4 length($recv_msg) is 28 (20 header + 8 payload)
788
+ # while IPv6 length is only 8 (sans header).
789
+ my $off = ($ip->{family} == AF_INET) ? 20 : 0; # payload offset
790
+ ($from_type, $from_subcode) = unpack("C2", substr($recv_msg, $off, 2));
791
+ if ($from_type == ICMP_TIMESTAMP_REPLY) {
792
+ ($from_pid, $from_seq) = unpack("n3", substr($recv_msg, $off + 4, 4))
793
+ if length $recv_msg >= $off + 8;
794
+ } elsif ($from_type == ICMP_ECHOREPLY || $from_type == ICMPv6_ECHOREPLY) {
795
+ #warn "ICMP_ECHOREPLY: ", $ip->{family}, " ",$recv_msg, ":", length($recv_msg);
796
+ ($from_pid, $from_seq) = unpack("n2", substr($recv_msg, $off + 4, 4))
797
+ if $recv_msg_len == $off + 8;
798
+ } elsif ($from_type == ICMPv6_NI_REPLY) {
799
+ ($from_pid, $from_seq) = unpack("n2", substr($recv_msg, 4, 4))
800
+ if ($ip->{family} == $AF_INET6 && length $recv_msg == 8);
801
+ } else {
802
+ #warn "ICMP: ", $from_type, " ",$ip->{family}, " ",$recv_msg, ":", length($recv_msg);
803
+ ($from_pid, $from_seq) = unpack("n2", substr($recv_msg, $off + 32, 4))
804
+ if length $recv_msg >= $off + 36;
805
+ }
806
+ $self->{from_ip} = $from_ip;
807
+ $self->{from_type} = $from_type;
808
+ $self->{from_subcode} = $from_subcode;
809
+ next if ($from_pid != $self->{pid});
810
+ next if ($from_seq != $self->{seq});
811
+ if (! $source_verify || ($self->ntop($from_ip) eq $self->ntop($ip))) { # Does the packet check out?
812
+ if (!$timestamp_msg && (($from_type == ICMP_ECHOREPLY) || ($from_type == ICMPv6_ECHOREPLY))) {
813
+ $ret = 1;
814
+ $done = 1;
815
+ } elsif ($timestamp_msg && $from_type == ICMP_TIMESTAMP_REPLY) {
816
+ $ret = 1;
817
+ $done = 1;
818
+ } elsif (($from_type == ICMP_UNREACHABLE) || ($from_type == ICMPv6_UNREACHABLE)) {
819
+ $done = 1;
820
+ } elsif ($from_type == ICMP_TIME_EXCEEDED) {
821
+ $ret = 0;
822
+ $done = 1;
823
+ }
824
+ }
825
+ } else { # Oops, timed out
826
+ $done = 1;
827
+ }
828
+ }
829
+ return $ret;
830
+ }
831
+
832
+ sub ping_icmpv6
833
+ {
834
+ shift->ping_icmp(@_);
835
+ }
836
+
837
+ sub icmp_result {
838
+ my ($self) = @_;
839
+ my $addr = $self->{from_ip} || "";
840
+ $addr = "\0\0\0\0" unless 4 == length $addr;
841
+ return ($self->ntop($addr),($self->{from_type} || 0), ($self->{from_subcode} || 0));
842
+ }
843
+
844
+ # Description: Do a checksum on the message. Basically sum all of
845
+ # the short words and fold the high order bits into the low order bits.
846
+
847
+ sub checksum
848
+ {
849
+ my ($class,
850
+ $msg # The message to checksum
851
+ ) = @_;
852
+ my ($len_msg, # Length of the message
853
+ $num_short, # The number of short words in the message
854
+ $short, # One short word
855
+ $chk # The checksum
856
+ );
857
+
858
+ $len_msg = length($msg);
859
+ $num_short = int($len_msg / 2);
860
+ $chk = 0;
861
+ foreach $short (unpack("n$num_short", $msg))
862
+ {
863
+ $chk += $short;
864
+ } # Add the odd byte in
865
+ $chk += (unpack("C", substr($msg, $len_msg - 1, 1)) << 8) if $len_msg % 2;
866
+ $chk = ($chk >> 16) + ($chk & 0xffff); # Fold high into low
867
+ return(~(($chk >> 16) + $chk) & 0xffff); # Again and complement
868
+ }
869
+
870
+
871
+ # Description: Perform a tcp echo ping. Since a tcp connection is
872
+ # host specific, we have to open and close each connection here. We
873
+ # can't just leave a socket open. Because of the robust nature of
874
+ # tcp, it will take a while before it gives up trying to establish a
875
+ # connection. Therefore, we use select() on a non-blocking socket to
876
+ # check against our timeout. No data bytes are actually
877
+ # sent since the successful establishment of a connection is proof
878
+ # enough of the reachability of the remote host. Also, tcp is
879
+ # expensive and doesn't need our help to add to the overhead.
880
+
881
+ sub ping_tcp
882
+ {
883
+ my ($self,
884
+ $ip, # Hash of addr (string), addr_in (packed), family
885
+ $timeout # Seconds after which ping times out
886
+ ) = @_;
887
+ my ($ret # The return value
888
+ );
889
+
890
+ $ip = $self->{host} if !defined $ip and $self->{host};
891
+ $timeout = $self->{timeout} if !defined $timeout and $self->{timeout};
892
+
893
+ $! = 0;
894
+ $ret = $self -> tcp_connect( $ip, $timeout);
895
+ if (!$self->{econnrefused} &&
896
+ $! == ECONNREFUSED) {
897
+ $ret = 1; # "Connection refused" means reachable
898
+ }
899
+ $self->{fh}->close();
900
+ return $ret;
901
+ }
902
+
903
+ sub tcp_connect
904
+ {
905
+ my ($self,
906
+ $ip, # Hash of addr (string), addr_in (packed), family
907
+ $timeout # Seconds after which connect times out
908
+ ) = @_;
909
+ my ($saddr); # Packed IP and Port
910
+
911
+ $ip = $self->{host} if !defined $ip and $self->{host};
912
+ $timeout = $self->{timeout} if !defined $timeout and $self->{timeout};
913
+
914
+ $saddr = _pack_sockaddr_in($self->{port_num}, $ip);
915
+
916
+ my $ret = 0; # Default to unreachable
917
+
918
+ my $do_socket = sub {
919
+ socket($self->{fh}, $ip->{family}, SOCK_STREAM, $self->{proto_num}) ||
920
+ croak("tcp socket error - $!");
921
+ if (defined $self->{local_addr} &&
922
+ !CORE::bind($self->{fh}, _pack_sockaddr_in(0, $self->{local_addr}))) {
923
+ croak("tcp bind error - $!");
924
+ }
925
+ $self->_setopts();
926
+ };
927
+ my $do_connect = sub {
928
+ $self->{ip} = $ip->{addr_in};
929
+ # ECONNREFUSED is 10061 on MSWin32. If we pass it as child error through $?,
930
+ # we'll get (10061 & 255) = 77, so we cannot check it in the parent process.
931
+ return ($ret = connect($self->{fh}, $saddr) || ($! == ECONNREFUSED && !$self->{econnrefused}));
932
+ };
933
+ my $do_connect_nb = sub {
934
+ # Set O_NONBLOCK property on filehandle
935
+ $self->socket_blocking_mode($self->{fh}, 0);
936
+
937
+ # start the connection attempt
938
+ if (!connect($self->{fh}, $saddr)) {
939
+ if ($! == ECONNREFUSED) {
940
+ $ret = 1 unless $self->{econnrefused};
941
+ } elsif ($! != EINPROGRESS && ($^O ne 'MSWin32' || $! != EWOULDBLOCK)) {
942
+ # EINPROGRESS is the expected error code after a connect()
943
+ # on a non-blocking socket. But if the kernel immediately
944
+ # determined that this connect() will never work,
945
+ # Simply respond with "unreachable" status.
946
+ # (This can occur on some platforms with errno
947
+ # EHOSTUNREACH or ENETUNREACH.)
948
+ return 0;
949
+ } else {
950
+ # Got the expected EINPROGRESS.
951
+ # Just wait for connection completion...
952
+ my ($wbits, $wout, $wexc);
953
+ $wout = $wexc = $wbits = "";
954
+ vec($wbits, $self->{fh}->fileno, 1) = 1;
955
+
956
+ my $nfound = mselect(undef,
957
+ ($wout = $wbits),
958
+ ($^O eq 'MSWin32' ? ($wexc = $wbits) : undef),
959
+ $timeout);
960
+ warn("select: $!") unless defined $nfound;
961
+
962
+ if ($nfound && vec($wout, $self->{fh}->fileno, 1)) {
963
+ # the socket is ready for writing so the connection
964
+ # attempt completed. test whether the connection
965
+ # attempt was successful or not
966
+
967
+ if (getpeername($self->{fh})) {
968
+ # Connection established to remote host
969
+ $ret = 1;
970
+ } else {
971
+ # TCP ACK will never come from this host
972
+ # because there was an error connecting.
973
+
974
+ # This should set $! to the correct error.
975
+ my $char;
976
+ sysread($self->{fh},$char,1);
977
+ $! = ECONNREFUSED if ($! == EAGAIN && $^O =~ /cygwin/i);
978
+
979
+ $ret = 1 if (!$self->{econnrefused}
980
+ && $! == ECONNREFUSED);
981
+ }
982
+ } else {
983
+ # the connection attempt timed out (or there were connect
984
+ # errors on Windows)
985
+ if ($^O =~ 'MSWin32') {
986
+ # If the connect will fail on a non-blocking socket,
987
+ # winsock reports ECONNREFUSED as an exception, and we
988
+ # need to fetch the socket-level error code via getsockopt()
989
+ # instead of using the thread-level error code that is in $!.
990
+ if ($nfound && vec($wexc, $self->{fh}->fileno, 1)) {
991
+ $! = unpack("i", getsockopt($self->{fh}, SOL_SOCKET,
992
+ SO_ERROR));
993
+ }
994
+ }
995
+ }
996
+ }
997
+ } else {
998
+ # Connection established to remote host
999
+ $ret = 1;
1000
+ }
1001
+
1002
+ # Unset O_NONBLOCK property on filehandle
1003
+ $self->socket_blocking_mode($self->{fh}, 1);
1004
+ $self->{ip} = $ip->{addr_in};
1005
+ return $ret;
1006
+ };
1007
+
1008
+ if ($syn_forking) {
1009
+ # Buggy Winsock API doesn't allow nonblocking connect.
1010
+ # Hence, if our OS is Windows, we need to create a separate
1011
+ # process to do the blocking connect attempt.
1012
+ # XXX Above comments are not true at least for Win2K, where
1013
+ # nonblocking connect works.
1014
+
1015
+ $| = 1; # Clear buffer prior to fork to prevent duplicate flushing.
1016
+ $self->{'tcp_chld'} = fork;
1017
+ if (!$self->{'tcp_chld'}) {
1018
+ if (!defined $self->{'tcp_chld'}) {
1019
+ # Fork did not work
1020
+ warn "Fork error: $!";
1021
+ return 0;
1022
+ }
1023
+ &{ $do_socket }();
1024
+
1025
+ # Try a slow blocking connect() call
1026
+ # and report the status to the parent.
1027
+ if ( &{ $do_connect }() ) {
1028
+ $self->{fh}->close();
1029
+ # No error
1030
+ exit 0;
1031
+ } else {
1032
+ # Pass the error status to the parent
1033
+ # Make sure that $! <= 255
1034
+ exit($! <= 255 ? $! : 255);
1035
+ }
1036
+ }
1037
+
1038
+ &{ $do_socket }();
1039
+
1040
+ my $patience = &time() + $timeout;
1041
+
1042
+ my ($child, $child_errno);
1043
+ $? = 0; $child_errno = 0;
1044
+ # Wait up to the timeout
1045
+ # And clean off the zombie
1046
+ do {
1047
+ $child = waitpid($self->{'tcp_chld'}, &WNOHANG());
1048
+ $child_errno = $? >> 8;
1049
+ select(undef, undef, undef, 0.1);
1050
+ } while &time() < $patience && $child != $self->{'tcp_chld'};
1051
+
1052
+ if ($child == $self->{'tcp_chld'}) {
1053
+ if ($self->{proto} eq "stream") {
1054
+ # We need the socket connected here, in parent
1055
+ # Should be safe to connect because the child finished
1056
+ # within the timeout
1057
+ &{ $do_connect }();
1058
+ }
1059
+ # $ret cannot be set by the child process
1060
+ $ret = !$child_errno;
1061
+ } else {
1062
+ # Time must have run out.
1063
+ # Put that choking client out of its misery
1064
+ kill "KILL", $self->{'tcp_chld'};
1065
+ # Clean off the zombie
1066
+ waitpid($self->{'tcp_chld'}, 0);
1067
+ $ret = 0;
1068
+ }
1069
+ delete $self->{'tcp_chld'};
1070
+ $! = $child_errno;
1071
+ } else {
1072
+ # Otherwise don't waste the resources to fork
1073
+
1074
+ &{ $do_socket }();
1075
+
1076
+ &{ $do_connect_nb }();
1077
+ }
1078
+
1079
+ return $ret;
1080
+ }
1081
+
1082
+ sub DESTROY {
1083
+ my $self = shift;
1084
+ if ($self->{'proto'} && ($self->{'proto'} eq 'tcp') && $self->{'tcp_chld'}) {
1085
+ # Put that choking client out of its misery
1086
+ kill "KILL", $self->{'tcp_chld'};
1087
+ # Clean off the zombie
1088
+ waitpid($self->{'tcp_chld'}, 0);
1089
+ }
1090
+ }
1091
+
1092
+ # This writes the given string to the socket and then reads it
1093
+ # back. It returns 1 on success, 0 on failure.
1094
+ sub tcp_echo
1095
+ {
1096
+ my ($self, $timeout, $pingstring) = @_;
1097
+
1098
+ $timeout = $self->{timeout} if !defined $timeout and $self->{timeout};
1099
+ $pingstring = $self->{pingstring} if !defined $pingstring and $self->{pingstring};
1100
+
1101
+ my $ret = undef;
1102
+ my $time = &time();
1103
+ my $wrstr = $pingstring;
1104
+ my $rdstr = "";
1105
+
1106
+ eval <<'EOM';
1107
+ do {
1108
+ my $rin = "";
1109
+ vec($rin, $self->{fh}->fileno(), 1) = 1;
1110
+
1111
+ my $rout = undef;
1112
+ if($wrstr) {
1113
+ $rout = "";
1114
+ vec($rout, $self->{fh}->fileno(), 1) = 1;
1115
+ }
1116
+
1117
+ if(mselect($rin, $rout, undef, ($time + $timeout) - &time())) {
1118
+
1119
+ if($rout && vec($rout,$self->{fh}->fileno(),1)) {
1120
+ my $num = syswrite($self->{fh}, $wrstr, length $wrstr);
1121
+ if($num) {
1122
+ # If it was a partial write, update and try again.
1123
+ $wrstr = substr($wrstr,$num);
1124
+ } else {
1125
+ # There was an error.
1126
+ $ret = 0;
1127
+ }
1128
+ }
1129
+
1130
+ if(vec($rin,$self->{fh}->fileno(),1)) {
1131
+ my $reply;
1132
+ if(sysread($self->{fh},$reply,length($pingstring)-length($rdstr))) {
1133
+ $rdstr .= $reply;
1134
+ $ret = 1 if $rdstr eq $pingstring;
1135
+ } else {
1136
+ # There was an error.
1137
+ $ret = 0;
1138
+ }
1139
+ }
1140
+
1141
+ }
1142
+ } until &time() > ($time + $timeout) || defined($ret);
1143
+ EOM
1144
+
1145
+ return $ret;
1146
+ }
1147
+
1148
+ # Description: Perform a stream ping. If the tcp connection isn't
1149
+ # already open, it opens it. It then sends some data and waits for
1150
+ # a reply. It leaves the stream open on exit.
1151
+
1152
+ sub ping_stream
1153
+ {
1154
+ my ($self,
1155
+ $ip, # Hash of addr (string), addr_in (packed), family
1156
+ $timeout # Seconds after which ping times out
1157
+ ) = @_;
1158
+
1159
+ # Open the stream if it's not already open
1160
+ if(!defined $self->{fh}->fileno()) {
1161
+ $self->tcp_connect($ip, $timeout) or return 0;
1162
+ }
1163
+
1164
+ croak "tried to switch servers while stream pinging"
1165
+ if $self->{ip} ne $ip->{addr_in};
1166
+
1167
+ return $self->tcp_echo($timeout, $pingstring);
1168
+ }
1169
+
1170
+ # Description: opens the stream. You would do this if you want to
1171
+ # separate the overhead of opening the stream from the first ping.
1172
+
1173
+ sub open
1174
+ {
1175
+ my ($self,
1176
+ $host, # Host or IP address
1177
+ $timeout, # Seconds after which open times out
1178
+ $family
1179
+ ) = @_;
1180
+ my $ip; # Hash of addr (string), addr_in (packed), family
1181
+ $host = $self->{host} unless defined $host;
1182
+
1183
+ if ($family) {
1184
+ if ($family =~ $qr_family) {
1185
+ if ($family =~ $qr_family4) {
1186
+ $self->{family_local} = AF_INET;
1187
+ } else {
1188
+ $self->{family_local} = $AF_INET6;
1189
+ }
1190
+ } else {
1191
+ croak('Family must be "ipv4" or "ipv6"')
1192
+ }
1193
+ } else {
1194
+ $self->{family_local} = $self->{family};
1195
+ }
1196
+
1197
+ $timeout = $self->{timeout} unless $timeout;
1198
+ $ip = $self->_resolv($host);
1199
+
1200
+ if ($self->{proto} eq "stream") {
1201
+ if (defined($self->{fh}->fileno())) {
1202
+ croak("socket is already open");
1203
+ } else {
1204
+ return () unless $ip;
1205
+ $self->tcp_connect($ip, $timeout);
1206
+ }
1207
+ }
1208
+ }
1209
+
1210
+ sub _dontfrag {
1211
+ my $self = shift;
1212
+ # bsd solaris
1213
+ my $IP_DONTFRAG = eval { Socket::IP_DONTFRAG() };
1214
+ if ($IP_DONTFRAG) {
1215
+ my $i = 1;
1216
+ setsockopt($self->{fh}, IPPROTO_IP, $IP_DONTFRAG, pack("I*", $i))
1217
+ or croak "error configuring IP_DONTFRAG $!";
1218
+ # Linux needs more: Path MTU Discovery as defined in RFC 1191
1219
+ # For non SOCK_STREAM sockets it is the user's responsibility to packetize
1220
+ # the data in MTU sized chunks and to do the retransmits if necessary.
1221
+ # The kernel will reject packets that are bigger than the known path
1222
+ # MTU if this flag is set (with EMSGSIZE).
1223
+ if ($^O eq 'linux') {
1224
+ my $i = 2; # IP_PMTUDISC_DO
1225
+ setsockopt($self->{fh}, IPPROTO_IP, IP_MTU_DISCOVER, pack("I*", $i))
1226
+ or croak "error configuring IP_MTU_DISCOVER $!";
1227
+ }
1228
+ }
1229
+ }
1230
+
1231
+ # SO_BINDTODEVICE + IP_TOS
1232
+ sub _setopts {
1233
+ my $self = shift;
1234
+ if ($self->{'device'}) {
1235
+ setsockopt($self->{fh}, SOL_SOCKET, SO_BINDTODEVICE, pack("Z*", $self->{'device'}))
1236
+ or croak "error binding to device $self->{'device'} $!";
1237
+ }
1238
+ if ($self->{'tos'}) { # need to re-apply ToS (RT #6706)
1239
+ setsockopt($self->{fh}, IPPROTO_IP, IP_TOS, pack("I*", $self->{'tos'}))
1240
+ or croak "error applying tos to $self->{'tos'} $!";
1241
+ }
1242
+ if ($self->{'dontfrag'}) {
1243
+ $self->_dontfrag;
1244
+ }
1245
+ }
1246
+
1247
+
1248
+ # Description: Perform a udp echo ping. Construct a message of
1249
+ # at least the one-byte sequence number and any additional data bytes.
1250
+ # Send the message out and wait for a message to come back. If we
1251
+ # get a message, make sure all of its parts match. If they do, we are
1252
+ # done. Otherwise go back and wait for the message until we run out
1253
+ # of time. Return the result of our efforts.
1254
+
1255
+ use constant UDP_FLAGS => 0; # Nothing special on send or recv
1256
+ sub ping_udp
1257
+ {
1258
+ my ($self,
1259
+ $ip, # Hash of addr (string), addr_in (packed), family
1260
+ $timeout # Seconds after which ping times out
1261
+ ) = @_;
1262
+
1263
+ my ($saddr, # sockaddr_in with port and ip
1264
+ $ret, # The return value
1265
+ $msg, # Message to be echoed
1266
+ $finish_time, # Time ping should be finished
1267
+ $flush, # Whether socket needs to be disconnected
1268
+ $connect, # Whether socket needs to be connected
1269
+ $done, # Set to 1 when we are done pinging
1270
+ $rbits, # Read bits, filehandles for reading
1271
+ $nfound, # Number of ready filehandles found
1272
+ $from_saddr, # sockaddr_in of sender
1273
+ $from_msg, # Characters echoed by $host
1274
+ $from_port, # Port message was echoed from
1275
+ $from_ip # Packed IP number of sender
1276
+ );
1277
+
1278
+ $saddr = _pack_sockaddr_in($self->{port_num}, $ip);
1279
+ $self->{seq} = ($self->{seq} + 1) % 256; # Increment sequence
1280
+ $msg = chr($self->{seq}) . $self->{data}; # Add data if any
1281
+
1282
+ socket($self->{fh}, $ip->{family}, SOCK_DGRAM,
1283
+ $self->{proto_num}) ||
1284
+ croak("udp socket error - $!");
1285
+
1286
+ if (defined $self->{local_addr} &&
1287
+ !CORE::bind($self->{fh}, _pack_sockaddr_in(0, $self->{local_addr}))) {
1288
+ croak("udp bind error - $!");
1289
+ }
1290
+
1291
+ $self->_setopts();
1292
+
1293
+ if ($self->{connected}) {
1294
+ if ($self->{connected} ne $saddr) {
1295
+ # Still connected to wrong destination.
1296
+ # Need to flush out the old one.
1297
+ $flush = 1;
1298
+ }
1299
+ } else {
1300
+ # Not connected yet.
1301
+ # Need to connect() before send()
1302
+ $connect = 1;
1303
+ }
1304
+
1305
+ # Have to connect() and send() instead of sendto()
1306
+ # in order to pick up on the ECONNREFUSED setting
1307
+ # from recv() or double send() errno as utilized in
1308
+ # the concept by rdw @ perlmonks. See:
1309
+ # http://perlmonks.thepen.com/42898.html
1310
+ if ($flush) {
1311
+ # Need to socket() again to flush the descriptor
1312
+ # This will disconnect from the old saddr.
1313
+ socket($self->{fh}, $ip->{family}, SOCK_DGRAM,
1314
+ $self->{proto_num});
1315
+ $self->_setopts();
1316
+ }
1317
+ # Connect the socket if it isn't already connected
1318
+ # to the right destination.
1319
+ if ($flush || $connect) {
1320
+ connect($self->{fh}, $saddr); # Tie destination to socket
1321
+ $self->{connected} = $saddr;
1322
+ }
1323
+ send($self->{fh}, $msg, UDP_FLAGS); # Send it
1324
+
1325
+ $rbits = "";
1326
+ vec($rbits, $self->{fh}->fileno(), 1) = 1;
1327
+ $ret = 0; # Default to unreachable
1328
+ $done = 0;
1329
+ my $retrans = 0.01;
1330
+ my $factor = $self->{retrans};
1331
+ $finish_time = &time() + $timeout; # Ping needs to be done by then
1332
+ while (!$done && $timeout > 0)
1333
+ {
1334
+ if ($factor > 1)
1335
+ {
1336
+ $timeout = $retrans if $timeout > $retrans;
1337
+ $retrans*= $factor; # Exponential backoff
1338
+ }
1339
+ $nfound = mselect((my $rout=$rbits), undef, undef, $timeout); # Wait for response
1340
+ my $why = $!;
1341
+ $timeout = $finish_time - &time(); # Get remaining time
1342
+
1343
+ if (!defined($nfound)) # Hmm, a strange error
1344
+ {
1345
+ $ret = undef;
1346
+ $done = 1;
1347
+ }
1348
+ elsif ($nfound) # A packet is waiting
1349
+ {
1350
+ $from_msg = "";
1351
+ $from_saddr = recv($self->{fh}, $from_msg, 1500, UDP_FLAGS);
1352
+ if (!$from_saddr) {
1353
+ # For example an unreachable host will make recv() fail.
1354
+ if (!$self->{econnrefused} &&
1355
+ ($! == ECONNREFUSED ||
1356
+ $! == ECONNRESET)) {
1357
+ # "Connection refused" means reachable
1358
+ # Good, continue
1359
+ $ret = 1;
1360
+ }
1361
+ $done = 1;
1362
+ } else {
1363
+ ($from_port, $from_ip) = _unpack_sockaddr_in($from_saddr, $ip->{family});
1364
+ my $addr_in = ref($ip) eq "HASH" ? $ip->{addr_in} : $ip;
1365
+ if (!$source_verify ||
1366
+ (($from_ip eq $addr_in) && # Does the packet check out?
1367
+ ($from_port == $self->{port_num}) &&
1368
+ ($from_msg eq $msg)))
1369
+ {
1370
+ $ret = 1; # It's a winner
1371
+ $done = 1;
1372
+ }
1373
+ }
1374
+ }
1375
+ elsif ($timeout <= 0) # Oops, timed out
1376
+ {
1377
+ $done = 1;
1378
+ }
1379
+ else
1380
+ {
1381
+ # Send another in case the last one dropped
1382
+ if (send($self->{fh}, $msg, UDP_FLAGS)) {
1383
+ # Another send worked? The previous udp packet
1384
+ # must have gotten lost or is still in transit.
1385
+ # Hopefully this new packet will arrive safely.
1386
+ } else {
1387
+ if (!$self->{econnrefused} &&
1388
+ $! == ECONNREFUSED) {
1389
+ # "Connection refused" means reachable
1390
+ # Good, continue
1391
+ $ret = 1;
1392
+ }
1393
+ $done = 1;
1394
+ }
1395
+ }
1396
+ }
1397
+ return $ret;
1398
+ }
1399
+
1400
+ # Description: Send a TCP SYN packet to host specified.
1401
+ sub ping_syn
1402
+ {
1403
+ my $self = shift;
1404
+ my $host = shift;
1405
+ my $ip = shift;
1406
+ my $start_time = shift;
1407
+ my $stop_time = shift;
1408
+
1409
+ if ($syn_forking) {
1410
+ return $self->ping_syn_fork($host, $ip, $start_time, $stop_time);
1411
+ }
1412
+
1413
+ my $fh = FileHandle->new();
1414
+ my $saddr = _pack_sockaddr_in($self->{port_num}, $ip);
1415
+
1416
+ # Create TCP socket
1417
+ if (!socket ($fh, $ip->{family}, SOCK_STREAM, $self->{proto_num})) {
1418
+ croak("tcp socket error - $!");
1419
+ }
1420
+
1421
+ if (defined $self->{local_addr} &&
1422
+ !CORE::bind($fh, _pack_sockaddr_in(0, $self->{local_addr}))) {
1423
+ croak("tcp bind error - $!");
1424
+ }
1425
+
1426
+ $self->_setopts();
1427
+ # Set O_NONBLOCK property on filehandle
1428
+ $self->socket_blocking_mode($fh, 0);
1429
+
1430
+ # Attempt the non-blocking connect
1431
+ # by just sending the TCP SYN packet
1432
+ if (connect($fh, $saddr)) {
1433
+ # Non-blocking, yet still connected?
1434
+ # Must have connected very quickly,
1435
+ # or else it wasn't very non-blocking.
1436
+ #warn "WARNING: Nonblocking connect connected anyway? ($^O)";
1437
+ } else {
1438
+ # Error occurred connecting.
1439
+ if ($! == EINPROGRESS || ($^O eq 'MSWin32' && $! == EWOULDBLOCK)) {
1440
+ # The connection is just still in progress.
1441
+ # This is the expected condition.
1442
+ } else {
1443
+ # Just save the error and continue on.
1444
+ # The ack() can check the status later.
1445
+ $self->{bad}->{$host} = $!;
1446
+ }
1447
+ }
1448
+
1449
+ my $entry = [ $host, $ip, $fh, $start_time, $stop_time, $self->{port_num} ];
1450
+ $self->{syn}->{$fh->fileno} = $entry;
1451
+ if ($self->{stop_time} < $stop_time) {
1452
+ $self->{stop_time} = $stop_time;
1453
+ }
1454
+ vec($self->{wbits}, $fh->fileno, 1) = 1;
1455
+
1456
+ return 1;
1457
+ }
1458
+
1459
+ sub ping_syn_fork {
1460
+ my ($self, $host, $ip, $start_time, $stop_time) = @_;
1461
+
1462
+ # Buggy Winsock API doesn't allow nonblocking connect.
1463
+ # Hence, if our OS is Windows, we need to create a separate
1464
+ # process to do the blocking connect attempt.
1465
+ my $pid = fork();
1466
+ if (defined $pid) {
1467
+ if ($pid) {
1468
+ # Parent process
1469
+ my $entry = [ $host, $ip, $pid, $start_time, $stop_time ];
1470
+ $self->{syn}->{$pid} = $entry;
1471
+ if ($self->{stop_time} < $stop_time) {
1472
+ $self->{stop_time} = $stop_time;
1473
+ }
1474
+ } else {
1475
+ # Child process
1476
+ my $saddr = _pack_sockaddr_in($self->{port_num}, $ip);
1477
+
1478
+ # Create TCP socket
1479
+ if (!socket ($self->{fh}, $ip->{family}, SOCK_STREAM, $self->{proto_num})) {
1480
+ croak("tcp socket error - $!");
1481
+ }
1482
+
1483
+ if (defined $self->{local_addr} &&
1484
+ !CORE::bind($self->{fh}, _pack_sockaddr_in(0, $self->{local_addr}))) {
1485
+ croak("tcp bind error - $!");
1486
+ }
1487
+
1488
+ $self->_setopts();
1489
+
1490
+ $!=0;
1491
+ # Try to connect (could take a long time)
1492
+ connect($self->{fh}, $saddr);
1493
+ # Notify parent of connect error status
1494
+ my $err = $!+0;
1495
+ my $wrstr = "$$ $err";
1496
+ # Force to 16 chars including \n
1497
+ $wrstr .= " "x(15 - length $wrstr). "\n";
1498
+ syswrite($self->{fork_wr}, $wrstr, length $wrstr);
1499
+ exit;
1500
+ }
1501
+ } else {
1502
+ # fork() failed?
1503
+ die "fork: $!";
1504
+ }
1505
+ return 1;
1506
+ }
1507
+
1508
+ # Description: Wait for TCP ACK from host specified
1509
+ # from ping_syn above. If no host is specified, wait
1510
+ # for TCP ACK from any of the hosts in the SYN queue.
1511
+ sub ack
1512
+ {
1513
+ my $self = shift;
1514
+
1515
+ if ($self->{proto} eq "syn") {
1516
+ if ($syn_forking) {
1517
+ my @answer = $self->ack_unfork(shift);
1518
+ return wantarray ? @answer : $answer[0];
1519
+ }
1520
+ my $wbits = "";
1521
+ my $stop_time = 0;
1522
+ if (my $host = shift or $self->{host}) {
1523
+ # Host passed as arg or as option to new
1524
+ $host = $self->{host} unless defined $host;
1525
+ if (exists $self->{bad}->{$host}) {
1526
+ if (!$self->{econnrefused} &&
1527
+ $self->{bad}->{ $host } &&
1528
+ (($! = ECONNREFUSED)>0) &&
1529
+ $self->{bad}->{ $host } eq "$!") {
1530
+ # "Connection refused" means reachable
1531
+ # Good, continue
1532
+ } else {
1533
+ # ECONNREFUSED means no good
1534
+ return ();
1535
+ }
1536
+ }
1537
+ my $host_fd = undef;
1538
+ foreach my $fd (keys %{ $self->{syn} }) {
1539
+ my $entry = $self->{syn}->{$fd};
1540
+ if ($entry->[0] eq $host) {
1541
+ $host_fd = $fd;
1542
+ $stop_time = $entry->[4]
1543
+ || croak("Corrupted SYN entry for [$host]");
1544
+ last;
1545
+ }
1546
+ }
1547
+ croak("ack called on [$host] without calling ping first!")
1548
+ unless defined $host_fd;
1549
+ vec($wbits, $host_fd, 1) = 1;
1550
+ } else {
1551
+ # No $host passed so scan all hosts
1552
+ # Use the latest stop_time
1553
+ $stop_time = $self->{stop_time};
1554
+ # Use all the bits
1555
+ $wbits = $self->{wbits};
1556
+ }
1557
+
1558
+ while ($wbits !~ /^\0*\z/) {
1559
+ my $timeout = $stop_time - &time();
1560
+ # Force a minimum of 10 ms timeout.
1561
+ $timeout = 0.01 if $timeout <= 0.01;
1562
+
1563
+ my $winner_fd = undef;
1564
+ my $wout = $wbits;
1565
+ my $fd = 0;
1566
+ # Do "bad" fds from $wbits first
1567
+ while ($wout !~ /^\0*\z/) {
1568
+ if (vec($wout, $fd, 1)) {
1569
+ # Wipe it from future scanning.
1570
+ vec($wout, $fd, 1) = 0;
1571
+ if (my $entry = $self->{syn}->{$fd}) {
1572
+ if ($self->{bad}->{ $entry->[0] }) {
1573
+ $winner_fd = $fd;
1574
+ last;
1575
+ }
1576
+ }
1577
+ }
1578
+ $fd++;
1579
+ }
1580
+
1581
+ if (defined($winner_fd) or my $nfound = mselect(undef, ($wout=$wbits), undef, $timeout)) {
1582
+ if (defined $winner_fd) {
1583
+ $fd = $winner_fd;
1584
+ } else {
1585
+ # Done waiting for one of the ACKs
1586
+ $fd = 0;
1587
+ # Determine which one
1588
+ while ($wout !~ /^\0*\z/ &&
1589
+ !vec($wout, $fd, 1)) {
1590
+ $fd++;
1591
+ }
1592
+ }
1593
+ if (my $entry = $self->{syn}->{$fd}) {
1594
+ # Wipe it from future scanning.
1595
+ delete $self->{syn}->{$fd};
1596
+ vec($self->{wbits}, $fd, 1) = 0;
1597
+ vec($wbits, $fd, 1) = 0;
1598
+ if (!$self->{econnrefused} &&
1599
+ $self->{bad}->{ $entry->[0] } &&
1600
+ (($! = ECONNREFUSED)>0) &&
1601
+ $self->{bad}->{ $entry->[0] } eq "$!") {
1602
+ # "Connection refused" means reachable
1603
+ # Good, continue
1604
+ } elsif (getpeername($entry->[2])) {
1605
+ # Connection established to remote host
1606
+ # Good, continue
1607
+ } else {
1608
+ # TCP ACK will never come from this host
1609
+ # because there was an error connecting.
1610
+
1611
+ # This should set $! to the correct error.
1612
+ my $char;
1613
+ sysread($entry->[2],$char,1);
1614
+ # Store the excuse why the connection failed.
1615
+ $self->{bad}->{$entry->[0]} = $!;
1616
+ if (!$self->{econnrefused} &&
1617
+ (($! == ECONNREFUSED) ||
1618
+ ($! == EAGAIN && $^O =~ /cygwin/i))) {
1619
+ # "Connection refused" means reachable
1620
+ # Good, continue
1621
+ } else {
1622
+ # No good, try the next socket...
1623
+ next;
1624
+ }
1625
+ }
1626
+ # Everything passed okay, return the answer
1627
+ return wantarray ?
1628
+ ($entry->[0], &time() - $entry->[3], $self->ntop($entry->[1]), $entry->[5])
1629
+ : $entry->[0];
1630
+ } else {
1631
+ warn "Corrupted SYN entry: unknown fd [$fd] ready!";
1632
+ vec($wbits, $fd, 1) = 0;
1633
+ vec($self->{wbits}, $fd, 1) = 0;
1634
+ }
1635
+ } elsif (defined $nfound) {
1636
+ # Timed out waiting for ACK
1637
+ foreach my $fd (keys %{ $self->{syn} }) {
1638
+ if (vec($wbits, $fd, 1)) {
1639
+ my $entry = $self->{syn}->{$fd};
1640
+ $self->{bad}->{$entry->[0]} = "Timed out";
1641
+ vec($wbits, $fd, 1) = 0;
1642
+ vec($self->{wbits}, $fd, 1) = 0;
1643
+ delete $self->{syn}->{$fd};
1644
+ }
1645
+ }
1646
+ } else {
1647
+ # Weird error occurred with select()
1648
+ warn("select: $!");
1649
+ $self->{syn} = {};
1650
+ $wbits = "";
1651
+ }
1652
+ }
1653
+ }
1654
+ return ();
1655
+ }
1656
+
1657
+ sub ack_unfork {
1658
+ my ($self,$host) = @_;
1659
+ my $stop_time = $self->{stop_time};
1660
+ if ($host) {
1661
+ # Host passed as arg
1662
+ if (my $entry = $self->{good}->{$host}) {
1663
+ delete $self->{good}->{$host};
1664
+ return ($entry->[0], &time() - $entry->[3], $self->ntop($entry->[1]));
1665
+ }
1666
+ }
1667
+
1668
+ my $rbits = "";
1669
+ my $timeout;
1670
+
1671
+ if (keys %{ $self->{syn} }) {
1672
+ # Scan all hosts that are left
1673
+ vec($rbits, fileno($self->{fork_rd}), 1) = 1;
1674
+ $timeout = $stop_time - &time();
1675
+ # Force a minimum of 10 ms timeout.
1676
+ $timeout = 0.01 if $timeout < 0.01;
1677
+ } else {
1678
+ # No hosts left to wait for
1679
+ $timeout = 0;
1680
+ }
1681
+
1682
+ if ($timeout > 0) {
1683
+ my $nfound;
1684
+ while ( keys %{ $self->{syn} } and
1685
+ $nfound = mselect((my $rout=$rbits), undef, undef, $timeout)) {
1686
+ # Done waiting for one of the ACKs
1687
+ if (!sysread($self->{fork_rd}, $_, 16)) {
1688
+ # Socket closed, which means all children are done.
1689
+ return ();
1690
+ }
1691
+ my ($pid, $how) = split;
1692
+ if ($pid) {
1693
+ # Flush the zombie
1694
+ waitpid($pid, 0);
1695
+ if (my $entry = $self->{syn}->{$pid}) {
1696
+ # Connection attempt to remote host is done
1697
+ delete $self->{syn}->{$pid};
1698
+ if (!$how || # If there was no error connecting
1699
+ (!$self->{econnrefused} &&
1700
+ $how == ECONNREFUSED)) { # "Connection refused" means reachable
1701
+ if ($host && $entry->[0] ne $host) {
1702
+ # A good connection, but not the host we need.
1703
+ # Move it from the "syn" hash to the "good" hash.
1704
+ $self->{good}->{$entry->[0]} = $entry;
1705
+ # And wait for the next winner
1706
+ next;
1707
+ }
1708
+ return ($entry->[0], &time() - $entry->[3], $self->ntop($entry->[1]));
1709
+ }
1710
+ } else {
1711
+ # Should never happen
1712
+ die "Unknown ping from pid [$pid]";
1713
+ }
1714
+ } else {
1715
+ die "Empty response from status socket?";
1716
+ }
1717
+ }
1718
+ if (defined $nfound) {
1719
+ # Timed out waiting for ACK status
1720
+ } else {
1721
+ # Weird error occurred with select()
1722
+ warn("select: $!");
1723
+ }
1724
+ }
1725
+ if (my @synners = keys %{ $self->{syn} }) {
1726
+ # Kill all the synners
1727
+ kill 9, @synners;
1728
+ foreach my $pid (@synners) {
1729
+ # Wait for the deaths to finish
1730
+ # Then flush off the zombie
1731
+ waitpid($pid, 0);
1732
+ }
1733
+ }
1734
+ $self->{syn} = {};
1735
+ return ();
1736
+ }
1737
+
1738
+ # Description: Tell why the ack() failed
1739
+ sub nack {
1740
+ my $self = shift;
1741
+ my $host = shift || croak('Usage> nack($failed_ack_host)');
1742
+ return $self->{bad}->{$host} || undef;
1743
+ }
1744
+
1745
+ # Description: Close the connection.
1746
+
1747
+ sub close
1748
+ {
1749
+ my ($self) = @_;
1750
+
1751
+ if ($self->{proto} eq "syn") {
1752
+ delete $self->{syn};
1753
+ } elsif ($self->{proto} eq "tcp") {
1754
+ # The connection will already be closed
1755
+ } elsif ($self->{proto} eq "external") {
1756
+ # Nothing to close
1757
+ } else {
1758
+ $self->{fh}->close();
1759
+ }
1760
+ }
1761
+
1762
+ sub port_number {
1763
+ my $self = shift;
1764
+ if(@_) {
1765
+ $self->{port_num} = shift @_;
1766
+ $self->service_check(1);
1767
+ }
1768
+ return $self->{port_num};
1769
+ }
1770
+
1771
+ sub ntop {
1772
+ my($self, $ip) = @_;
1773
+
1774
+ # Vista doesn't define a inet_ntop. It has InetNtop instead.
1775
+ # Not following ANSI... priceless. getnameinfo() is defined
1776
+ # for Windows 2000 and later, so that may be the choice.
1777
+
1778
+ # Any port will work, even undef, but this will work for now.
1779
+ # Socket warns when undef is passed in, but it still works.
1780
+ my $port = getservbyname('echo', 'udp');
1781
+ my $sockaddr = _pack_sockaddr_in($port, $ip);
1782
+ my ($error, $address) = getnameinfo($sockaddr, $NI_NUMERICHOST);
1783
+ croak $error if $error;
1784
+ return $address;
1785
+ }
1786
+
1787
+ sub wakeonlan {
1788
+ my ($mac_addr, $host, $port) = @_;
1789
+
1790
+ # use the discard service if $port not passed in
1791
+ if (! defined $host) { $host = '255.255.255.255' }
1792
+ if (! defined $port || $port !~ /^\d+$/ ) { $port = 9 }
1793
+
1794
+ require IO::Socket::INET;
1795
+ my $sock = IO::Socket::INET->new(Proto=>'udp') || return undef;
1796
+
1797
+ my $ip_addr = inet_aton($host);
1798
+ my $sock_addr = sockaddr_in($port, $ip_addr);
1799
+ $mac_addr =~ s/://g;
1800
+ my $packet = pack('C6H*', 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, $mac_addr x 16);
1801
+
1802
+ setsockopt($sock, SOL_SOCKET, SO_BROADCAST, 1);
1803
+ send($sock, $packet, 0, $sock_addr);
1804
+ $sock->close;
1805
+
1806
+ return 1;
1807
+ }
1808
+
1809
+ ########################################################
1810
+ # DNS hostname resolution
1811
+ # return:
1812
+ # $h->{name} = host - as passed in
1813
+ # $h->{host} = host - as passed in without :port
1814
+ # $h->{port} = OPTIONAL - if :port, then value of port
1815
+ # $h->{addr} = resolved numeric address
1816
+ # $h->{addr_in} = aton/pton result
1817
+ # $h->{family} = AF_INET/6
1818
+ ############################
1819
+ sub _resolv {
1820
+ my ($self,
1821
+ $name,
1822
+ ) = @_;
1823
+
1824
+ my %h;
1825
+ $h{name} = $name;
1826
+ my $family = $self->{family};
1827
+
1828
+ if (defined($self->{family_local})) {
1829
+ $family = $self->{family_local}
1830
+ }
1831
+
1832
+ # START - host:port
1833
+ my $cnt = 0;
1834
+
1835
+ # Count ":"
1836
+ $cnt++ while ($name =~ m/:/g);
1837
+
1838
+ # 0 = hostname or IPv4 address
1839
+ if ($cnt == 0) {
1840
+ $h{host} = $name
1841
+ # 1 = IPv4 address with port
1842
+ } elsif ($cnt == 1) {
1843
+ ($h{host}, $h{port}) = split /:/, $name
1844
+ # >=2 = IPv6 address
1845
+ } elsif ($cnt >= 2) {
1846
+ #IPv6 with port - [2001::1]:port
1847
+ if ($name =~ /^\[.*\]:\d{1,5}$/) {
1848
+ ($h{host}, $h{port}) = split /:([^:]+)$/, $name # split after last :
1849
+ # IPv6 without port
1850
+ } else {
1851
+ $h{host} = $name
1852
+ }
1853
+ }
1854
+
1855
+ # Clean up host
1856
+ $h{host} =~ s/\[//g;
1857
+ $h{host} =~ s/\]//g;
1858
+ # Clean up port
1859
+ if (defined($h{port}) && (($h{port} !~ /^\d{1,5}$/) || ($h{port} < 1) || ($h{port} > 65535))) {
1860
+ croak("Invalid port `$h{port}' in `$name'");
1861
+ return undef;
1862
+ }
1863
+ # END - host:port
1864
+
1865
+ # address check
1866
+ # new way
1867
+ if ($Socket_VERSION > 1.94) {
1868
+ my %hints = (
1869
+ family => $AF_UNSPEC,
1870
+ protocol => IPPROTO_TCP,
1871
+ flags => $AI_NUMERICHOST
1872
+ );
1873
+
1874
+ # numeric address, return
1875
+ my ($err, @getaddr) = Socket::getaddrinfo($h{host}, undef, \%hints);
1876
+ if (defined($getaddr[0])) {
1877
+ $h{addr} = $h{host};
1878
+ $h{family} = $getaddr[0]->{family};
1879
+ if ($h{family} == AF_INET) {
1880
+ (undef, $h{addr_in}, undef, undef) = Socket::unpack_sockaddr_in $getaddr[0]->{addr};
1881
+ } else {
1882
+ (undef, $h{addr_in}, undef, undef) = Socket::unpack_sockaddr_in6 $getaddr[0]->{addr};
1883
+ }
1884
+ return \%h
1885
+ }
1886
+ # old way
1887
+ } else {
1888
+ # numeric address, return
1889
+ my $ret = gethostbyname($h{host});
1890
+ if (defined($ret) && (_inet_ntoa($ret) eq $h{host})) {
1891
+ $h{addr} = $h{host};
1892
+ $h{addr_in} = $ret;
1893
+ $h{family} = AF_INET;
1894
+ return \%h
1895
+ }
1896
+ }
1897
+
1898
+ # resolve
1899
+ # new way
1900
+ if ($Socket_VERSION >= 1.94) {
1901
+ my %hints = (
1902
+ family => $family,
1903
+ protocol => IPPROTO_TCP
1904
+ );
1905
+
1906
+ my ($err, @getaddr) = Socket::getaddrinfo($h{host}, undef, \%hints);
1907
+ if (defined($getaddr[0])) {
1908
+ my ($err, $address) = Socket::getnameinfo($getaddr[0]->{addr}, $NI_NUMERICHOST, $NIx_NOSERV);
1909
+ if (defined($address)) {
1910
+ $h{addr} = $address;
1911
+ $h{addr} =~ s/\%(.)*$//; # remove %ifID if IPv6
1912
+ $h{family} = $getaddr[0]->{family};
1913
+ if ($h{family} == AF_INET) {
1914
+ (undef, $h{addr_in}, undef, undef) = Socket::unpack_sockaddr_in $getaddr[0]->{addr};
1915
+ } else {
1916
+ (undef, $h{addr_in}, undef, undef) = Socket::unpack_sockaddr_in6 $getaddr[0]->{addr};
1917
+ }
1918
+ return \%h;
1919
+ } else {
1920
+ carp("getnameinfo($getaddr[0]->{addr}) failed - $err");
1921
+ return undef;
1922
+ }
1923
+ } else {
1924
+ warn(sprintf("getaddrinfo($h{host},,%s) failed - $err",
1925
+ $family == AF_INET ? "AF_INET" : "AF_INET6"));
1926
+ return undef;
1927
+ }
1928
+ # old way
1929
+ } else {
1930
+ if ($family == $AF_INET6) {
1931
+ croak("Socket >= 1.94 required for IPv6 - found Socket $Socket::VERSION");
1932
+ return undef;
1933
+ }
1934
+
1935
+ my @gethost = gethostbyname($h{host});
1936
+ if (defined($gethost[4])) {
1937
+ $h{addr} = inet_ntoa($gethost[4]);
1938
+ $h{addr_in} = $gethost[4];
1939
+ $h{family} = AF_INET;
1940
+ return \%h
1941
+ } else {
1942
+ carp("gethostbyname($h{host}) failed - $^E");
1943
+ return undef;
1944
+ }
1945
+ }
1946
+ return undef;
1947
+ }
1948
+
1949
+ sub _pack_sockaddr_in($$) {
1950
+ my ($port,
1951
+ $ip,
1952
+ ) = @_;
1953
+
1954
+ my $addr = ref($ip) eq "HASH" ? $ip->{addr_in} : $ip;
1955
+ if (length($addr) <= 4 ) {
1956
+ return Socket::pack_sockaddr_in($port, $addr);
1957
+ } else {
1958
+ return Socket::pack_sockaddr_in6($port, $addr);
1959
+ }
1960
+ }
1961
+
1962
+ sub _unpack_sockaddr_in($;$) {
1963
+ my ($addr,
1964
+ $family,
1965
+ ) = @_;
1966
+
1967
+ my ($port, $host);
1968
+ if ($family == AF_INET || (!defined($family) and length($addr) <= 16 )) {
1969
+ ($port, $host) = Socket::unpack_sockaddr_in($addr);
1970
+ } else {
1971
+ ($port, $host) = Socket::unpack_sockaddr_in6($addr);
1972
+ }
1973
+ return $port, $host
1974
+ }
1975
+
1976
+ sub _inet_ntoa {
1977
+ my ($addr
1978
+ ) = @_;
1979
+
1980
+ my $ret;
1981
+ if ($Socket_VERSION >= 1.94) {
1982
+ my ($err, $address) = Socket::getnameinfo($addr, $NI_NUMERICHOST);
1983
+ if (defined($address)) {
1984
+ $ret = $address;
1985
+ } else {
1986
+ carp("getnameinfo($addr) failed - $err");
1987
+ }
1988
+ } else {
1989
+ $ret = inet_ntoa($addr)
1990
+ }
1991
+
1992
+ return $ret
1993
+ }
1994
+
1995
+ 1;
1996
+ __END__
1997
+
1998
+ =head1 NAME
1999
+
2000
+ Net::Ping - check a remote host for reachability
2001
+
2002
+ =head1 SYNOPSIS
2003
+
2004
+ use Net::Ping;
2005
+
2006
+ my $p = Net::Ping->new();
2007
+ print "$host is alive.\n" if $p->ping($host);
2008
+ $p->close();
2009
+
2010
+ my $p = Net::Ping->new("icmp");
2011
+ $p->bind($my_addr); # Specify source interface of pings
2012
+ foreach my $host (@host_array)
2013
+ {
2014
+ print "$host is ";
2015
+ print "NOT " unless $p->ping($host, 2);
2016
+ print "reachable.\n";
2017
+ sleep(1);
2018
+ }
2019
+ $p->close();
2020
+
2021
+ my $p = Net::Ping->new("icmpv6");
2022
+ my $ip = "[fd00:dead:beef::4e]";
2023
+ print "$ip is alive.\n" if $p->ping($ip);
2024
+
2025
+ my $p = Net::Ping->new("tcp", 2);
2026
+ # Try connecting to the www port instead of the echo port
2027
+ $p->port_number(scalar(getservbyname("http", "tcp")));
2028
+ while ($stop_time > time())
2029
+ {
2030
+ print "$host not reachable ", scalar(localtime()), "\n"
2031
+ unless $p->ping($host);
2032
+ sleep(300);
2033
+ }
2034
+ undef($p);
2035
+
2036
+ # Like tcp protocol, but with many hosts
2037
+ my $p = Net::Ping->new("syn");
2038
+ $p->port_number(getservbyname("http", "tcp"));
2039
+ foreach my $host (@host_array) {
2040
+ $p->ping($host);
2041
+ }
2042
+ while (my ($host, $rtt, $ip) = $p->ack) {
2043
+ print "HOST: $host [$ip] ACKed in $rtt seconds.\n";
2044
+ }
2045
+
2046
+ # High precision syntax (requires Time::HiRes)
2047
+ my $p = Net::Ping->new();
2048
+ $p->hires();
2049
+ my ($ret, $duration, $ip) = $p->ping($host, 5.5);
2050
+ printf("$host [ip: $ip] is alive (packet return time: %.2f ms)\n",
2051
+ 1000 * $duration)
2052
+ if $ret;
2053
+ $p->close();
2054
+
2055
+ # For backward compatibility
2056
+ print "$host is alive.\n" if pingecho($host);
2057
+
2058
+ =head1 DESCRIPTION
2059
+
2060
+ This module contains methods to test the reachability of remote
2061
+ hosts on a network. A ping object is first created with optional
2062
+ parameters, a variable number of hosts may be pinged multiple
2063
+ times and then the connection is closed.
2064
+
2065
+ You may choose one of six different protocols to use for the
2066
+ ping. The "tcp" protocol is the default. Note that a live remote host
2067
+ may still fail to be pingable by one or more of these protocols. For
2068
+ example, www.microsoft.com is generally alive but not "icmp" pingable.
2069
+
2070
+ With the "tcp" protocol the ping() method attempts to establish a
2071
+ connection to the remote host's echo port. If the connection is
2072
+ successfully established, the remote host is considered reachable. No
2073
+ data is actually echoed. This protocol does not require any special
2074
+ privileges but has higher overhead than the "udp" and "icmp" protocols.
2075
+
2076
+ Specifying the "udp" protocol causes the ping() method to send a udp
2077
+ packet to the remote host's echo port. If the echoed packet is
2078
+ received from the remote host and the received packet contains the
2079
+ same data as the packet that was sent, the remote host is considered
2080
+ reachable. This protocol does not require any special privileges.
2081
+ It should be borne in mind that, for a udp ping, a host
2082
+ will be reported as unreachable if it is not running the
2083
+ appropriate echo service. For Unix-like systems see L<inetd(8)>
2084
+ for more information.
2085
+
2086
+ If the "icmp" protocol is specified, the ping() method sends an icmp
2087
+ echo message to the remote host, which is what the UNIX ping program
2088
+ does. If the echoed message is received from the remote host and
2089
+ the echoed information is correct, the remote host is considered
2090
+ reachable. Specifying the "icmp" protocol requires that the program
2091
+ be run as root or that the program be setuid to root.
2092
+
2093
+ If the "external" protocol is specified, the ping() method attempts to
2094
+ use the C<Net::Ping::External> module to ping the remote host.
2095
+ C<Net::Ping::External> interfaces with your system's default C<ping>
2096
+ utility to perform the ping, and generally produces relatively
2097
+ accurate results. If C<Net::Ping::External> if not installed on your
2098
+ system, specifying the "external" protocol will result in an error.
2099
+
2100
+ If the "syn" protocol is specified, the L</ping> method will only
2101
+ send a TCP SYN packet to the remote host then immediately return.
2102
+ If the syn packet was sent successfully, it will return a true value,
2103
+ otherwise it will return false. NOTE: Unlike the other protocols,
2104
+ the return value does NOT determine if the remote host is alive or
2105
+ not since the full TCP three-way handshake may not have completed
2106
+ yet. The remote host is only considered reachable if it receives
2107
+ a TCP ACK within the timeout specified. To begin waiting for the
2108
+ ACK packets, use the L</ack> method as explained below. Use the
2109
+ "syn" protocol instead the "tcp" protocol to determine reachability
2110
+ of multiple destinations simultaneously by sending parallel TCP
2111
+ SYN packets. It will not block while testing each remote host.
2112
+ This protocol does not require any special privileges.
2113
+
2114
+ =head2 Functions
2115
+
2116
+ =over 4
2117
+
2118
+ =item Net::Ping->new([proto, timeout, bytes, device, tos, ttl, family,
2119
+ host, port, bind, gateway, retrans, pingstring,
2120
+ source_verify econnrefused dontfrag
2121
+ IPV6_USE_MIN_MTU IPV6_RECVPATHMTU])
2122
+ X<new>
2123
+
2124
+ Create a new ping object. All of the parameters are optional and can
2125
+ be passed as hash ref. All options besides the first 7 must be passed
2126
+ as hash ref.
2127
+
2128
+ C<proto> specifies the protocol to use when doing a ping. The current
2129
+ choices are "tcp", "udp", "icmp", "icmpv6", "stream", "syn", or
2130
+ "external". The default is "tcp".
2131
+
2132
+ If a C<timeout> in seconds is provided, it is used
2133
+ when a timeout is not given to the ping() method (below). The timeout
2134
+ must be greater than 0 and the default, if not specified, is 5 seconds.
2135
+
2136
+ If the number of data bytes (C<bytes>) is given, that many data bytes
2137
+ are included in the ping packet sent to the remote host. The number of
2138
+ data bytes is ignored if the protocol is "tcp". The minimum (and
2139
+ default) number of data bytes is 1 if the protocol is "udp" and 0
2140
+ otherwise. The maximum number of data bytes that can be specified is
2141
+ 65535, but staying below the MTU (1472 bytes for ICMP) is recommended.
2142
+ Many small devices cannot deal with fragmented ICMP packets.
2143
+
2144
+ If C<device> is given, this device is used to bind the source endpoint
2145
+ before sending the ping packet. I believe this only works with
2146
+ superuser privileges and with udp and icmp protocols at this time.
2147
+
2148
+ If <tos> is given, this ToS is configured into the socket.
2149
+
2150
+ For icmp, C<ttl> can be specified to set the TTL of the outgoing packet.
2151
+
2152
+ Valid C<family> values for IPv4:
2153
+
2154
+ 4, v4, ip4, ipv4, AF_INET (constant)
2155
+
2156
+ Valid C<family> values for IPv6:
2157
+
2158
+ 6, v6, ip6, ipv6, AF_INET6 (constant)
2159
+
2160
+ The C<host> argument implicitly specifies the family if the family
2161
+ argument is not given.
2162
+
2163
+ The C<port> argument is only valid for a udp, tcp or stream ping, and will not
2164
+ do what you think it does. ping returns true when we get a "Connection refused"!
2165
+ The default is the echo port.
2166
+
2167
+ The C<bind> argument specifies the local_addr to bind to.
2168
+ By specifying a bind argument you don't need the bind method.
2169
+
2170
+ The C<gateway> argument is only valid for IPv6, and requires a IPv6
2171
+ address.
2172
+
2173
+ The C<retrans> argument the exponential backoff rate, default 1.2.
2174
+ It matches the $def_factor global.
2175
+
2176
+ The C<dontfrag> argument sets the IP_DONTFRAG bit, but note that
2177
+ IP_DONTFRAG is not yet defined by Socket, and not available on many
2178
+ systems. Then it is ignored. On linux it also sets IP_MTU_DISCOVER to
2179
+ IP_PMTUDISC_DO but need we don't chunk oversized packets. You need to
2180
+ set $data_size manually.
2181
+
2182
+ =item $p->ping($host [, $timeout [, $family]]);
2183
+ X<ping>
2184
+
2185
+ Ping the remote host and wait for a response. $host can be either the
2186
+ hostname or the IP number of the remote host. The optional timeout
2187
+ must be greater than 0 seconds and defaults to whatever was specified
2188
+ when the ping object was created. Returns a success flag. If the
2189
+ hostname cannot be found or there is a problem with the IP number, the
2190
+ success flag returned will be undef. Otherwise, the success flag will
2191
+ be 1 if the host is reachable and 0 if it is not. For most practical
2192
+ purposes, undef and 0 and can be treated as the same case. In array
2193
+ context, the elapsed time as well as the string form of the ip the
2194
+ host resolved to are also returned. The elapsed time value will
2195
+ be a float, as returned by the Time::HiRes::time() function, if hires()
2196
+ has been previously called, otherwise it is returned as an integer.
2197
+
2198
+ =item $p->source_verify( { 0 | 1 } );
2199
+ X<source_verify>
2200
+
2201
+ Allows source endpoint verification to be enabled or disabled.
2202
+ This is useful for those remote destinations with multiples
2203
+ interfaces where the response may not originate from the same
2204
+ endpoint that the original destination endpoint was sent to.
2205
+ This only affects udp and icmp protocol pings.
2206
+
2207
+ This is enabled by default.
2208
+
2209
+ =item $p->service_check( { 0 | 1 } );
2210
+ X<service_check>
2211
+
2212
+ Set whether or not the connect behavior should enforce
2213
+ remote service availability as well as reachability. Normally,
2214
+ if the remote server reported ECONNREFUSED, it must have been
2215
+ reachable because of the status packet that it reported.
2216
+ With this option enabled, the full three-way tcp handshake
2217
+ must have been established successfully before it will
2218
+ claim it is reachable. NOTE: It still does nothing more
2219
+ than connect and disconnect. It does not speak any protocol
2220
+ (i.e., HTTP or FTP) to ensure the remote server is sane in
2221
+ any way. The remote server CPU could be grinding to a halt
2222
+ and unresponsive to any clients connecting, but if the kernel
2223
+ throws the ACK packet, it is considered alive anyway. To
2224
+ really determine if the server is responding well would be
2225
+ application specific and is beyond the scope of Net::Ping.
2226
+ For udp protocol, enabling this option demands that the
2227
+ remote server replies with the same udp data that it was sent
2228
+ as defined by the udp echo service.
2229
+
2230
+ This affects the "udp", "tcp", and "syn" protocols.
2231
+
2232
+ This is disabled by default.
2233
+
2234
+ =item $p->tcp_service_check( { 0 | 1 } );
2235
+ X<tcp_service_check>
2236
+
2237
+ Deprecated method, but does the same as service_check() method.
2238
+
2239
+ =item $p->hires( { 0 | 1 } );
2240
+ X<hires>
2241
+
2242
+ With 1 causes this module to use Time::HiRes module, allowing milliseconds
2243
+ to be returned by subsequent calls to ping().
2244
+
2245
+ =item $p->time
2246
+ X<time>
2247
+
2248
+ The current time, hires or not.
2249
+
2250
+ =item $p->socket_blocking_mode( $fh, $mode );
2251
+ X<socket_blocking_mode>
2252
+
2253
+ Sets or clears the O_NONBLOCK flag on a file handle.
2254
+
2255
+ =item $p->IPV6_USE_MIN_MTU
2256
+ X<IPV6_USE_MIN_MTU>
2257
+
2258
+ With argument sets the option.
2259
+ Without returns the option value.
2260
+
2261
+ =item $p->IPV6_RECVPATHMTU
2262
+ X<IPV6_RECVPATHMTU>
2263
+
2264
+ Notify an according IPv6 MTU.
2265
+
2266
+ With argument sets the option.
2267
+ Without returns the option value.
2268
+
2269
+ =item $p->IPV6_HOPLIMIT
2270
+ X<IPV6_HOPLIMIT>
2271
+
2272
+ With argument sets the option.
2273
+ Without returns the option value.
2274
+
2275
+ =item $p->IPV6_REACHCONF I<NYI>
2276
+ X<IPV6_REACHCONF>
2277
+
2278
+ Sets ipv6 reachability
2279
+ IPV6_REACHCONF was removed in RFC3542. ping6 -R supports it.
2280
+ IPV6_REACHCONF requires root/admin permissions.
2281
+
2282
+ With argument sets the option.
2283
+ Without returns the option value.
2284
+
2285
+ Not yet implemented.
2286
+
2287
+ =item $p->bind($local_addr);
2288
+ X<bind>
2289
+
2290
+ Sets the source address from which pings will be sent. This must be
2291
+ the address of one of the interfaces on the local host. $local_addr
2292
+ may be specified as a hostname or as a text IP address such as
2293
+ "192.168.1.1".
2294
+
2295
+ If the protocol is set to "tcp", this method may be called any
2296
+ number of times, and each call to the ping() method (below) will use
2297
+ the most recent $local_addr. If the protocol is "icmp" or "udp",
2298
+ then bind() must be called at most once per object, and (if it is
2299
+ called at all) must be called before the first call to ping() for that
2300
+ object.
2301
+
2302
+ The bind() call can be omitted when specifying the C<bind> option to
2303
+ new().
2304
+
2305
+ =item $p->message_type([$ping_type]);
2306
+ X<message_type>
2307
+
2308
+ When you are using the "icmp" protocol, this call permit to change the
2309
+ message type to 'echo' or 'timestamp' (only for IPv4, see RFC 792).
2310
+
2311
+ Without argument, it returns the currently used icmp protocol message type.
2312
+ By default, it returns 'echo'.
2313
+
2314
+ =item $p->open($host);
2315
+ X<open>
2316
+
2317
+ When you are using the "stream" protocol, this call pre-opens the
2318
+ tcp socket. It's only necessary to do this if you want to
2319
+ provide a different timeout when creating the connection, or
2320
+ remove the overhead of establishing the connection from the
2321
+ first ping. If you don't call C<open()>, the connection is
2322
+ automatically opened the first time C<ping()> is called.
2323
+ This call simply does nothing if you are using any protocol other
2324
+ than stream.
2325
+
2326
+ The $host argument can be omitted when specifying the C<host> option to
2327
+ new().
2328
+
2329
+ =item $p->ack( [ $host ] );
2330
+ X<ack>
2331
+
2332
+ When using the "syn" protocol, use this method to determine
2333
+ the reachability of the remote host. This method is meant
2334
+ to be called up to as many times as ping() was called. Each
2335
+ call returns the host (as passed to ping()) that came back
2336
+ with the TCP ACK. The order in which the hosts are returned
2337
+ may not necessarily be the same order in which they were
2338
+ SYN queued using the ping() method. If the timeout is
2339
+ reached before the TCP ACK is received, or if the remote
2340
+ host is not listening on the port attempted, then the TCP
2341
+ connection will not be established and ack() will return
2342
+ undef. In list context, the host, the ack time, the dotted ip
2343
+ string, and the port number will be returned instead of just the host.
2344
+ If the optional C<$host> argument is specified, the return
2345
+ value will be pertaining to that host only.
2346
+ This call simply does nothing if you are using any protocol
2347
+ other than "syn".
2348
+
2349
+ When L</new> had a host option, this host will be used.
2350
+ Without C<$host> argument, all hosts are scanned.
2351
+
2352
+ =item $p->nack( $failed_ack_host );
2353
+ X<nack>
2354
+
2355
+ The reason that C<host $failed_ack_host> did not receive a
2356
+ valid ACK. Useful to find out why when C<ack($fail_ack_host)>
2357
+ returns a false value.
2358
+
2359
+ =item $p->ack_unfork($host)
2360
+ X<ack_unfork>
2361
+
2362
+ The variant called by L</ack> with the "syn" protocol and C<$syn_forking>
2363
+ enabled.
2364
+
2365
+ =item $p->ping_icmp([$host, $timeout, $family])
2366
+ X<ping_icmp>
2367
+
2368
+ The L</ping> method used with the icmp protocol.
2369
+
2370
+ =item $p->ping_icmpv6([$host, $timeout, $family])
2371
+ X<ping_icmpv6>
2372
+
2373
+ The L</ping> method used with the icmpv6 protocol.
2374
+
2375
+ =item $p->ping_stream([$host, $timeout, $family])
2376
+ X<ping_stream>
2377
+
2378
+ The L</ping> method used with the stream protocol.
2379
+
2380
+ Perform a stream ping. If the tcp connection isn't
2381
+ already open, it opens it. It then sends some data and waits for
2382
+ a reply. It leaves the stream open on exit.
2383
+
2384
+ =item $p->ping_syn([$host, $ip, $start_time, $stop_time])
2385
+ X<ping_syn>
2386
+
2387
+ The L</ping> method used with the syn protocol.
2388
+ Sends a TCP SYN packet to host specified.
2389
+
2390
+ =item $p->ping_syn_fork([$host, $timeout, $family])
2391
+ X<ping_syn_fork>
2392
+
2393
+ The L</ping> method used with the forking syn protocol.
2394
+
2395
+ =item $p->ping_tcp([$host, $timeout, $family])
2396
+ X<ping_tcp>
2397
+
2398
+ The L</ping> method used with the tcp protocol.
2399
+
2400
+ =item $p->ping_udp([$host, $timeout, $family])
2401
+ X<ping_udp>
2402
+
2403
+ The L</ping> method used with the udp protocol.
2404
+
2405
+ Perform a udp echo ping. Construct a message of
2406
+ at least the one-byte sequence number and any additional data bytes.
2407
+ Send the message out and wait for a message to come back. If we
2408
+ get a message, make sure all of its parts match. If they do, we are
2409
+ done. Otherwise go back and wait for the message until we run out
2410
+ of time. Return the result of our efforts.
2411
+
2412
+ =item $p->ping_external([$host, $timeout, $family])
2413
+ X<ping_external>
2414
+
2415
+ The L</ping> method used with the external protocol.
2416
+ Uses L<Net::Ping::External> to do an external ping.
2417
+
2418
+ =item $p->tcp_connect([$ip, $timeout])
2419
+ X<tcp_connect>
2420
+
2421
+ Initiates a TCP connection, for a tcp ping.
2422
+
2423
+ =item $p->tcp_echo([$ip, $timeout, $pingstring])
2424
+ X<tcp_echo>
2425
+
2426
+ Performs a TCP echo.
2427
+ It writes the given string to the socket and then reads it
2428
+ back. It returns 1 on success, 0 on failure.
2429
+
2430
+ =item $p->close();
2431
+ X<close>
2432
+
2433
+ Close the network connection for this ping object. The network
2434
+ connection is also closed by "undef $p". The network connection is
2435
+ automatically closed if the ping object goes out of scope (e.g. $p is
2436
+ local to a subroutine and you leave the subroutine).
2437
+
2438
+ =item $p->port_number([$port_number])
2439
+ X<port_number>
2440
+
2441
+ When called with a port number, the port number used to ping is set to
2442
+ C<$port_number> rather than using the echo port. It also has the effect
2443
+ of calling C<$p-E<gt>service_check(1)> causing a ping to return a successful
2444
+ response only if that specific port is accessible. This function returns
2445
+ the value of the port that L</ping> will connect to.
2446
+
2447
+ =item $p->mselect
2448
+ X<mselect>
2449
+
2450
+ A C<select()> wrapper that compensates for platform
2451
+ peculiarities.
2452
+
2453
+ =item $p->ntop
2454
+ X<ntop>
2455
+
2456
+ Platform abstraction over C<inet_ntop()>
2457
+
2458
+ =item $p->checksum($msg)
2459
+ X<checksum>
2460
+
2461
+ Do a checksum on the message. Basically sum all of
2462
+ the short words and fold the high order bits into the low order bits.
2463
+
2464
+ =item $p->icmp_result
2465
+ X<icmp_result>
2466
+
2467
+ Returns a list of addr, type, subcode.
2468
+
2469
+ =item pingecho($host [, $timeout]);
2470
+ X<pingecho>
2471
+
2472
+ To provide backward compatibility with the previous version of
2473
+ L<Net::Ping>, a C<pingecho()> subroutine is available with the same
2474
+ functionality as before. C<pingecho()> uses the tcp protocol. The
2475
+ return values and parameters are the same as described for the L</ping>
2476
+ method. This subroutine is obsolete and may be removed in a future
2477
+ version of L<Net::Ping>.
2478
+
2479
+ =item wakeonlan($mac, [$host, [$port]])
2480
+ X<wakeonlan>
2481
+
2482
+ Emit the popular wake-on-lan magic udp packet to wake up a local
2483
+ device. See also L<Net::Wake>, but this has the mac address as 1st arg.
2484
+ C<$host> should be the local gateway. Without it will broadcast.
2485
+
2486
+ Default host: '255.255.255.255'
2487
+ Default port: 9
2488
+
2489
+ perl -MNet::Ping=wakeonlan -e'wakeonlan "e0:69:95:35:68:d2"'
2490
+
2491
+ =back
2492
+
2493
+ =head1 NOTES
2494
+
2495
+ There will be less network overhead (and some efficiency in your
2496
+ program) if you specify either the udp or the icmp protocol. The tcp
2497
+ protocol will generate 2.5 times or more traffic for each ping than
2498
+ either udp or icmp. If many hosts are pinged frequently, you may wish
2499
+ to implement a small wait (e.g. 25ms or more) between each ping to
2500
+ avoid flooding your network with packets.
2501
+
2502
+ The icmp and icmpv6 protocols requires that the program be run as root
2503
+ or that it be setuid to root. The other protocols do not require
2504
+ special privileges, but not all network devices implement tcp or udp
2505
+ echo.
2506
+
2507
+ Local hosts should normally respond to pings within milliseconds.
2508
+ However, on a very congested network it may take up to 3 seconds or
2509
+ longer to receive an echo packet from the remote host. If the timeout
2510
+ is set too low under these conditions, it will appear that the remote
2511
+ host is not reachable (which is almost the truth).
2512
+
2513
+ Reachability doesn't necessarily mean that the remote host is actually
2514
+ functioning beyond its ability to echo packets. tcp is slightly better
2515
+ at indicating the health of a system than icmp because it uses more
2516
+ of the networking stack to respond.
2517
+
2518
+ Because of a lack of anything better, this module uses its own
2519
+ routines to pack and unpack ICMP packets. It would be better for a
2520
+ separate module to be written which understands all of the different
2521
+ kinds of ICMP packets.
2522
+
2523
+ =head1 INSTALL
2524
+
2525
+ The latest source tree is available via git:
2526
+
2527
+ git clone https://github.com/rurban/Net-Ping.git
2528
+ cd Net-Ping
2529
+
2530
+ The tarball can be created as follows:
2531
+
2532
+ perl Makefile.PL ; make ; make dist
2533
+
2534
+ The latest Net::Ping releases are included in cperl and perl5.
2535
+
2536
+ =head1 BUGS
2537
+
2538
+ For a list of known issues, visit:
2539
+
2540
+ L<https://rt.cpan.org/NoAuth/Bugs.html?Dist=Net-Ping>
2541
+ and
2542
+ L<https://github.com/rurban/Net-Ping/issues>
2543
+
2544
+ To report a new bug, visit:
2545
+
2546
+ L<https://github.com/rurban/Net-Ping/issues>
2547
+
2548
+ =head1 AUTHORS
2549
+
2550
+ Current maintainers:
2551
+ perl11 (for cperl, with IPv6 support and more)
2552
+ p5p (for perl5)
2553
+
2554
+ Previous maintainers:
2555
+ bbb@cpan.org (Rob Brown)
2556
+ Steve Peters
2557
+
2558
+ External protocol:
2559
+ colinm@cpan.org (Colin McMillen)
2560
+
2561
+ Stream protocol:
2562
+ bronson@trestle.com (Scott Bronson)
2563
+
2564
+ Wake-on-lan:
2565
+ 1999-2003 Clinton Wong
2566
+
2567
+ Original pingecho():
2568
+ karrer@bernina.ethz.ch (Andreas Karrer)
2569
+ pmarquess@bfsec.bt.co.uk (Paul Marquess)
2570
+
2571
+ Original Net::Ping author:
2572
+ mose@ns.ccsn.edu (Russell Mosemann)
2573
+
2574
+ =head1 COPYRIGHT
2575
+
2576
+ Copyright (c) 2017-2020, Reini Urban. All rights reserved.
2577
+
2578
+ Copyright (c) 2016, cPanel Inc. All rights reserved.
2579
+
2580
+ Copyright (c) 2012, Steve Peters. All rights reserved.
2581
+
2582
+ Copyright (c) 2002-2003, Rob Brown. All rights reserved.
2583
+
2584
+ Copyright (c) 2001, Colin McMillen. All rights reserved.
2585
+
2586
+ This program is free software; you may redistribute it and/or
2587
+ modify it under the same terms as Perl itself.
2588
+
2589
+ =cut
git/usr/share/perl5/core_perl/Net/SMTP.pm ADDED
@@ -0,0 +1,1065 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Net::SMTP.pm
2
+ #
3
+ # Copyright (C) 1995-2004 Graham Barr. All rights reserved.
4
+ # Copyright (C) 2013-2016, 2020 Steve Hay. All rights reserved.
5
+ # This module is free software; you can redistribute it and/or modify it under
6
+ # the same terms as Perl itself, i.e. under the terms of either the GNU General
7
+ # Public License or the Artistic License, as specified in the F<LICENCE> file.
8
+
9
+ package Net::SMTP;
10
+
11
+ use 5.008001;
12
+
13
+ use strict;
14
+ use warnings;
15
+
16
+ use Carp;
17
+ use IO::Socket;
18
+ use Net::Cmd;
19
+ use Net::Config;
20
+ use Socket;
21
+
22
+ our $VERSION = "3.15";
23
+
24
+ # Code for detecting if we can use SSL
25
+ my $ssl_class = eval {
26
+ require IO::Socket::SSL;
27
+ # first version with default CA on most platforms
28
+ no warnings 'numeric';
29
+ IO::Socket::SSL->VERSION(2.007);
30
+ } && 'IO::Socket::SSL';
31
+
32
+ my $nossl_warn = !$ssl_class &&
33
+ 'To use SSL please install IO::Socket::SSL with version>=2.007';
34
+
35
+ # Code for detecting if we can use IPv6
36
+ my $family_key = 'Domain';
37
+ my $inet6_class = eval {
38
+ require IO::Socket::IP;
39
+ no warnings 'numeric';
40
+ IO::Socket::IP->VERSION(0.25) || die;
41
+ $family_key = 'Family';
42
+ } && 'IO::Socket::IP' || eval {
43
+ require IO::Socket::INET6;
44
+ no warnings 'numeric';
45
+ IO::Socket::INET6->VERSION(2.62);
46
+ } && 'IO::Socket::INET6';
47
+
48
+ sub can_ssl { $ssl_class };
49
+ sub can_inet6 { $inet6_class };
50
+
51
+ our @ISA = ('Net::Cmd', $inet6_class || 'IO::Socket::INET');
52
+
53
+ sub new {
54
+ my $self = shift;
55
+ my $type = ref($self) || $self;
56
+ my ($host, %arg);
57
+ if (@_ % 2) {
58
+ $host = shift;
59
+ %arg = @_;
60
+ }
61
+ else {
62
+ %arg = @_;
63
+ $host = delete $arg{Host};
64
+ }
65
+
66
+ if ($arg{SSL}) {
67
+ # SSL from start
68
+ die $nossl_warn if !$ssl_class;
69
+ $arg{Port} ||= 465;
70
+ }
71
+
72
+ my $hosts = defined $host ? $host : $NetConfig{smtp_hosts};
73
+ my $obj;
74
+
75
+ $arg{Timeout} = 120 if ! defined $arg{Timeout};
76
+
77
+ foreach my $h (@{ref($hosts) ? $hosts : [$hosts]}) {
78
+ $obj = $type->SUPER::new(
79
+ PeerAddr => ($host = $h),
80
+ PeerPort => $arg{Port} || 'smtp(25)',
81
+ LocalAddr => $arg{LocalAddr},
82
+ LocalPort => $arg{LocalPort},
83
+ $family_key => $arg{Domain} || $arg{Family},
84
+ Proto => 'tcp',
85
+ Timeout => $arg{Timeout}
86
+ )
87
+ and last;
88
+ }
89
+
90
+ return
91
+ unless defined $obj;
92
+
93
+ ${*$obj}{'net_smtp_arg'} = \%arg;
94
+ ${*$obj}{'net_smtp_host'} = $host;
95
+
96
+ if ($arg{SSL}) {
97
+ Net::SMTP::_SSL->start_SSL($obj,%arg)
98
+ or return;
99
+ }
100
+
101
+ $obj->autoflush(1);
102
+
103
+ $obj->debug(exists $arg{Debug} ? $arg{Debug} : undef);
104
+
105
+ unless ($obj->response() == CMD_OK) {
106
+ my $err = ref($obj) . ": " . $obj->code . " " . $obj->message;
107
+ $obj->close();
108
+ $@ = $err;
109
+ return;
110
+ }
111
+
112
+ ${*$obj}{'net_smtp_exact_addr'} = $arg{ExactAddresses};
113
+
114
+ (${*$obj}{'net_smtp_banner'}) = $obj->message;
115
+ (${*$obj}{'net_smtp_domain'}) = $obj->message =~ /\A\s*(\S+)/;
116
+
117
+ if (!exists $arg{SendHello} || $arg{SendHello}) {
118
+ unless ($obj->hello($arg{Hello} || "")) {
119
+ my $err = ref($obj) . ": " . $obj->code . " " . $obj->message;
120
+ $obj->close();
121
+ $@ = $err;
122
+ return;
123
+ }
124
+ }
125
+
126
+ $obj;
127
+ }
128
+
129
+
130
+ sub host {
131
+ my $me = shift;
132
+ ${*$me}{'net_smtp_host'};
133
+ }
134
+
135
+ ##
136
+ ## User interface methods
137
+ ##
138
+
139
+
140
+ sub banner {
141
+ my $me = shift;
142
+
143
+ return ${*$me}{'net_smtp_banner'} || undef;
144
+ }
145
+
146
+
147
+ sub domain {
148
+ my $me = shift;
149
+
150
+ return ${*$me}{'net_smtp_domain'} || undef;
151
+ }
152
+
153
+
154
+ sub etrn {
155
+ my $self = shift;
156
+ defined($self->supports('ETRN', 500, ["Command unknown: 'ETRN'"]))
157
+ && $self->_ETRN(@_);
158
+ }
159
+
160
+
161
+ sub auth {
162
+ my ($self, $username, $password) = @_;
163
+
164
+ eval {
165
+ require MIME::Base64;
166
+ require Authen::SASL;
167
+ } or $self->set_status(500, ["Need MIME::Base64 and Authen::SASL todo auth"]), return 0;
168
+
169
+ my $mechanisms = $self->supports('AUTH', 500, ["Command unknown: 'AUTH'"]);
170
+ return unless defined $mechanisms;
171
+
172
+ my $sasl;
173
+
174
+ if (ref($username) and UNIVERSAL::isa($username, 'Authen::SASL')) {
175
+ $sasl = $username;
176
+ my $requested_mechanisms = $sasl->mechanism();
177
+ if (! defined($requested_mechanisms) || $requested_mechanisms eq '') {
178
+ $sasl->mechanism($mechanisms);
179
+ }
180
+ }
181
+ else {
182
+ die "auth(username, password)" if not length $username;
183
+ $sasl = Authen::SASL->new(
184
+ mechanism => $mechanisms,
185
+ callback => {
186
+ user => $username,
187
+ pass => $password,
188
+ authname => $username,
189
+ },
190
+ debug => $self->debug
191
+ );
192
+ }
193
+
194
+ my $client;
195
+ my $str;
196
+ do {
197
+ if ($client) {
198
+ # $client mechanism failed, so we need to exclude this mechanism from list
199
+ my $failed_mechanism = $client->mechanism;
200
+ return unless defined $failed_mechanism;
201
+ $self->debug_text("Auth mechanism failed: $failed_mechanism")
202
+ if $self->debug;
203
+ $mechanisms =~ s/\b\Q$failed_mechanism\E\b//;
204
+ return unless $mechanisms =~ /\S/;
205
+ $sasl->mechanism($mechanisms);
206
+ }
207
+
208
+ # We should probably allow the user to pass the host, but I don't
209
+ # currently know and SASL mechanisms that are used by smtp that need it
210
+
211
+ $client = $sasl->client_new('smtp', ${*$self}{'net_smtp_host'}, 0);
212
+ $str = $client->client_start;
213
+ } while (!defined $str);
214
+
215
+ # We don't support sasl mechanisms that encrypt the socket traffic.
216
+ # todo that we would really need to change the ISA hierarchy
217
+ # so we don't inherit from IO::Socket, but instead hold it in an attribute
218
+
219
+ my @cmd = ("AUTH", $client->mechanism);
220
+ my $code;
221
+
222
+ push @cmd, MIME::Base64::encode_base64($str, '')
223
+ if defined $str and length $str;
224
+
225
+ while (($code = $self->command(@cmd)->response()) == CMD_MORE) {
226
+ my $str2 = MIME::Base64::decode_base64(($self->message)[0]);
227
+ $self->debug_print(0, "(decoded) " . $str2 . "\n") if $self->debug;
228
+
229
+ $str = $client->client_step($str2);
230
+ @cmd = (
231
+ MIME::Base64::encode_base64($str, '')
232
+ );
233
+
234
+ $self->debug_print(1, "(decoded) " . $str . "\n") if $self->debug;
235
+ }
236
+
237
+ $code == CMD_OK;
238
+ }
239
+
240
+
241
+ sub hello {
242
+ my $me = shift;
243
+ my $domain = shift || "localhost.localdomain";
244
+ my $ok = $me->_EHLO($domain);
245
+ my @msg = $me->message;
246
+
247
+ if ($ok) {
248
+ my $h = ${*$me}{'net_smtp_esmtp'} = {};
249
+ foreach my $ln (@msg) {
250
+ $h->{uc $1} = $2
251
+ if $ln =~ /([-\w]+)\b[= \t]*([^\n]*)/;
252
+ }
253
+ }
254
+ elsif ($me->status == CMD_ERROR) {
255
+ @msg = $me->message
256
+ if $ok = $me->_HELO($domain);
257
+ }
258
+
259
+ return unless $ok;
260
+ ${*$me}{net_smtp_hello_domain} = $domain;
261
+
262
+ $msg[0] =~ /\A\s*(\S+)/;
263
+ return ($1 || " ");
264
+ }
265
+
266
+ sub starttls {
267
+ my $self = shift;
268
+ $ssl_class or die $nossl_warn;
269
+ $self->_STARTTLS or return;
270
+ Net::SMTP::_SSL->start_SSL($self,
271
+ %{ ${*$self}{'net_smtp_arg'} }, # (ssl) args given in new
272
+ @_ # more (ssl) args
273
+ ) or return;
274
+
275
+ # another hello after starttls to read new ESMTP capabilities
276
+ return $self->hello(${*$self}{net_smtp_hello_domain});
277
+ }
278
+
279
+
280
+ sub supports {
281
+ my $self = shift;
282
+ my $cmd = uc shift;
283
+ return ${*$self}{'net_smtp_esmtp'}->{$cmd}
284
+ if exists ${*$self}{'net_smtp_esmtp'}->{$cmd};
285
+ $self->set_status(@_)
286
+ if @_;
287
+ return;
288
+ }
289
+
290
+
291
+ sub _addr {
292
+ my $self = shift;
293
+ my $addr = shift;
294
+ $addr = "" unless defined $addr;
295
+
296
+ if (${*$self}{'net_smtp_exact_addr'}) {
297
+ return $1 if $addr =~ /^\s*(<.*>)\s*$/s;
298
+ }
299
+ else {
300
+ return $1 if $addr =~ /(<[^>]*>)/;
301
+ $addr =~ s/^\s+|\s+$//sg;
302
+ }
303
+
304
+ "<$addr>";
305
+ }
306
+
307
+
308
+ sub mail {
309
+ my $me = shift;
310
+ my $addr = _addr($me, shift);
311
+ my $opts = "";
312
+
313
+ if (@_) {
314
+ my %opt = @_;
315
+ my ($k, $v);
316
+
317
+ if (exists ${*$me}{'net_smtp_esmtp'}) {
318
+ my $esmtp = ${*$me}{'net_smtp_esmtp'};
319
+
320
+ if (defined($v = delete $opt{Size})) {
321
+ if (exists $esmtp->{SIZE}) {
322
+ $opts .= sprintf " SIZE=%d", $v + 0;
323
+ }
324
+ else {
325
+ carp 'Net::SMTP::mail: SIZE option not supported by host';
326
+ }
327
+ }
328
+
329
+ if (defined($v = delete $opt{Return})) {
330
+ if (exists $esmtp->{DSN}) {
331
+ $opts .= " RET=" . ((uc($v) eq "FULL") ? "FULL" : "HDRS");
332
+ }
333
+ else {
334
+ carp 'Net::SMTP::mail: DSN option not supported by host';
335
+ }
336
+ }
337
+
338
+ if (defined($v = delete $opt{Bits})) {
339
+ if ($v eq "8") {
340
+ if (exists $esmtp->{'8BITMIME'}) {
341
+ $opts .= " BODY=8BITMIME";
342
+ }
343
+ else {
344
+ carp 'Net::SMTP::mail: 8BITMIME option not supported by host';
345
+ }
346
+ }
347
+ elsif ($v eq "binary") {
348
+ if (exists $esmtp->{'BINARYMIME'} && exists $esmtp->{'CHUNKING'}) {
349
+ $opts .= " BODY=BINARYMIME";
350
+ ${*$me}{'net_smtp_chunking'} = 1;
351
+ }
352
+ else {
353
+ carp 'Net::SMTP::mail: BINARYMIME option not supported by host';
354
+ }
355
+ }
356
+ elsif (exists $esmtp->{'8BITMIME'} or exists $esmtp->{'BINARYMIME'}) {
357
+ $opts .= " BODY=7BIT";
358
+ }
359
+ else {
360
+ carp 'Net::SMTP::mail: 8BITMIME and BINARYMIME options not supported by host';
361
+ }
362
+ }
363
+
364
+ if (defined($v = delete $opt{Transaction})) {
365
+ if (exists $esmtp->{CHECKPOINT}) {
366
+ $opts .= " TRANSID=" . _addr($me, $v);
367
+ }
368
+ else {
369
+ carp 'Net::SMTP::mail: CHECKPOINT option not supported by host';
370
+ }
371
+ }
372
+
373
+ if (defined($v = delete $opt{Envelope})) {
374
+ if (exists $esmtp->{DSN}) {
375
+ $v =~ s/([^\041-\176]|=|\+)/sprintf "+%02X", ord($1)/sge;
376
+ $opts .= " ENVID=$v";
377
+ }
378
+ else {
379
+ carp 'Net::SMTP::mail: DSN option not supported by host';
380
+ }
381
+ }
382
+
383
+ if (defined($v = delete $opt{ENVID})) {
384
+
385
+ # expected to be in a format as required by RFC 3461, xtext-encoded
386
+ if (exists $esmtp->{DSN}) {
387
+ $opts .= " ENVID=$v";
388
+ }
389
+ else {
390
+ carp 'Net::SMTP::mail: DSN option not supported by host';
391
+ }
392
+ }
393
+
394
+ if (defined($v = delete $opt{AUTH})) {
395
+
396
+ # expected to be in a format as required by RFC 2554,
397
+ # rfc2821-quoted and xtext-encoded, or <>
398
+ if (exists $esmtp->{AUTH}) {
399
+ $v = '<>' if !defined($v) || $v eq '';
400
+ $opts .= " AUTH=$v";
401
+ }
402
+ else {
403
+ carp 'Net::SMTP::mail: AUTH option not supported by host';
404
+ }
405
+ }
406
+
407
+ if (defined($v = delete $opt{XVERP})) {
408
+ if (exists $esmtp->{'XVERP'}) {
409
+ $opts .= " XVERP";
410
+ }
411
+ else {
412
+ carp 'Net::SMTP::mail: XVERP option not supported by host';
413
+ }
414
+ }
415
+
416
+ carp 'Net::SMTP::recipient: unknown option(s) ' . join(" ", keys %opt) . ' - ignored'
417
+ if scalar keys %opt;
418
+ }
419
+ else {
420
+ carp 'Net::SMTP::mail: ESMTP not supported by host - options discarded :-(';
421
+ }
422
+ }
423
+
424
+ $me->_MAIL("FROM:" . $addr . $opts);
425
+ }
426
+
427
+
428
+ sub send { my $me = shift; $me->_SEND("FROM:" . _addr($me, $_[0])) }
429
+ sub send_or_mail { my $me = shift; $me->_SOML("FROM:" . _addr($me, $_[0])) }
430
+ sub send_and_mail { my $me = shift; $me->_SAML("FROM:" . _addr($me, $_[0])) }
431
+
432
+
433
+ sub reset {
434
+ my $me = shift;
435
+
436
+ $me->dataend()
437
+ if (exists ${*$me}{'net_smtp_lastch'});
438
+
439
+ $me->_RSET();
440
+ }
441
+
442
+
443
+ sub recipient {
444
+ my $smtp = shift;
445
+ my $opts = "";
446
+ my $skip_bad = 0;
447
+
448
+ if (@_ && ref($_[-1])) {
449
+ my %opt = %{pop(@_)};
450
+ my $v;
451
+
452
+ $skip_bad = delete $opt{'SkipBad'};
453
+
454
+ if (exists ${*$smtp}{'net_smtp_esmtp'}) {
455
+ my $esmtp = ${*$smtp}{'net_smtp_esmtp'};
456
+
457
+ if (defined($v = delete $opt{Notify})) {
458
+ if (exists $esmtp->{DSN}) {
459
+ $opts .= " NOTIFY=" . join(",", map { uc $_ } @$v);
460
+ }
461
+ else {
462
+ carp 'Net::SMTP::recipient: DSN option not supported by host';
463
+ }
464
+ }
465
+
466
+ if (defined($v = delete $opt{ORcpt})) {
467
+ if (exists $esmtp->{DSN}) {
468
+ $opts .= " ORCPT=" . $v;
469
+ }
470
+ else {
471
+ carp 'Net::SMTP::recipient: DSN option not supported by host';
472
+ }
473
+ }
474
+
475
+ carp 'Net::SMTP::recipient: unknown option(s) ' . join(" ", keys %opt) . ' - ignored'
476
+ if scalar keys %opt;
477
+ }
478
+ elsif (%opt) {
479
+ carp 'Net::SMTP::recipient: ESMTP not supported by host - options discarded :-(';
480
+ }
481
+ }
482
+
483
+ my @ok;
484
+ foreach my $addr (@_) {
485
+ if ($smtp->_RCPT("TO:" . _addr($smtp, $addr) . $opts)) {
486
+ push(@ok, $addr) if $skip_bad;
487
+ }
488
+ elsif (!$skip_bad) {
489
+ return 0;
490
+ }
491
+ }
492
+
493
+ return $skip_bad ? @ok : 1;
494
+ }
495
+
496
+ BEGIN {
497
+ *to = \&recipient;
498
+ *cc = \&recipient;
499
+ *bcc = \&recipient;
500
+ }
501
+
502
+
503
+ sub data {
504
+ my $me = shift;
505
+
506
+ if (exists ${*$me}{'net_smtp_chunking'}) {
507
+ carp 'Net::SMTP::data: CHUNKING extension in use, must call bdat instead';
508
+ }
509
+ else {
510
+ my $ok = $me->_DATA() && $me->datasend(@_);
511
+
512
+ $ok && @_
513
+ ? $me->dataend
514
+ : $ok;
515
+ }
516
+ }
517
+
518
+
519
+ sub bdat {
520
+ my $me = shift;
521
+
522
+ if (exists ${*$me}{'net_smtp_chunking'}) {
523
+ my $data = shift;
524
+
525
+ $me->_BDAT(length $data)
526
+ && $me->rawdatasend($data)
527
+ && $me->response() == CMD_OK;
528
+ }
529
+ else {
530
+ carp 'Net::SMTP::bdat: CHUNKING extension is not in use, call data instead';
531
+ }
532
+ }
533
+
534
+
535
+ sub bdatlast {
536
+ my $me = shift;
537
+
538
+ if (exists ${*$me}{'net_smtp_chunking'}) {
539
+ my $data = shift;
540
+
541
+ $me->_BDAT(length $data, "LAST")
542
+ && $me->rawdatasend($data)
543
+ && $me->response() == CMD_OK;
544
+ }
545
+ else {
546
+ carp 'Net::SMTP::bdat: CHUNKING extension is not in use, call data instead';
547
+ }
548
+ }
549
+
550
+
551
+ sub datafh {
552
+ my $me = shift;
553
+ return unless $me->_DATA();
554
+ return $me->tied_fh;
555
+ }
556
+
557
+
558
+ sub expand {
559
+ my $me = shift;
560
+
561
+ $me->_EXPN(@_)
562
+ ? ($me->message)
563
+ : ();
564
+ }
565
+
566
+
567
+ sub verify { shift->_VRFY(@_) }
568
+
569
+
570
+ sub help {
571
+ my $me = shift;
572
+
573
+ $me->_HELP(@_)
574
+ ? scalar $me->message
575
+ : undef;
576
+ }
577
+
578
+
579
+ sub quit {
580
+ my $me = shift;
581
+
582
+ $me->_QUIT;
583
+ $me->close;
584
+ }
585
+
586
+
587
+ sub DESTROY {
588
+
589
+ # ignore
590
+ }
591
+
592
+ ##
593
+ ## RFC821 commands
594
+ ##
595
+
596
+
597
+ sub _EHLO { shift->command("EHLO", @_)->response() == CMD_OK }
598
+ sub _HELO { shift->command("HELO", @_)->response() == CMD_OK }
599
+ sub _MAIL { shift->command("MAIL", @_)->response() == CMD_OK }
600
+ sub _RCPT { shift->command("RCPT", @_)->response() == CMD_OK }
601
+ sub _SEND { shift->command("SEND", @_)->response() == CMD_OK }
602
+ sub _SAML { shift->command("SAML", @_)->response() == CMD_OK }
603
+ sub _SOML { shift->command("SOML", @_)->response() == CMD_OK }
604
+ sub _VRFY { shift->command("VRFY", @_)->response() == CMD_OK }
605
+ sub _EXPN { shift->command("EXPN", @_)->response() == CMD_OK }
606
+ sub _HELP { shift->command("HELP", @_)->response() == CMD_OK }
607
+ sub _RSET { shift->command("RSET")->response() == CMD_OK }
608
+ sub _NOOP { shift->command("NOOP")->response() == CMD_OK }
609
+ sub _QUIT { shift->command("QUIT")->response() == CMD_OK }
610
+ sub _DATA { shift->command("DATA")->response() == CMD_MORE }
611
+ sub _BDAT { shift->command("BDAT", @_) }
612
+ sub _TURN { shift->unsupported(@_); }
613
+ sub _ETRN { shift->command("ETRN", @_)->response() == CMD_OK }
614
+ sub _AUTH { shift->command("AUTH", @_)->response() == CMD_OK }
615
+ sub _STARTTLS { shift->command("STARTTLS")->response() == CMD_OK }
616
+
617
+
618
+ {
619
+ package Net::SMTP::_SSL;
620
+ our @ISA = ( $ssl_class ? ($ssl_class):(), 'Net::SMTP' );
621
+ sub starttls { die "SMTP connection is already in SSL mode" }
622
+ sub start_SSL {
623
+ my ($class,$smtp,%arg) = @_;
624
+ delete @arg{ grep { !m{^SSL_} } keys %arg };
625
+ ( $arg{SSL_verifycn_name} ||= $smtp->host )
626
+ =~s{(?<!:):[\w()]+$}{}; # strip port
627
+ $arg{SSL_hostname} = $arg{SSL_verifycn_name}
628
+ if ! defined $arg{SSL_hostname} && $class->can_client_sni;
629
+ $arg{SSL_verifycn_scheme} ||= 'smtp';
630
+ my $ok = $class->SUPER::start_SSL($smtp,%arg);
631
+ $@ = $ssl_class->errstr if !$ok;
632
+ return $ok;
633
+ }
634
+ }
635
+
636
+
637
+
638
+ 1;
639
+
640
+ __END__
641
+
642
+ =head1 NAME
643
+
644
+ Net::SMTP - Simple Mail Transfer Protocol Client
645
+
646
+ =head1 SYNOPSIS
647
+
648
+ use Net::SMTP;
649
+
650
+ # Constructors
651
+ $smtp = Net::SMTP->new('mailhost');
652
+ $smtp = Net::SMTP->new('mailhost', Timeout => 60);
653
+
654
+ =head1 DESCRIPTION
655
+
656
+ This module implements a client interface to the SMTP and ESMTP
657
+ protocol, enabling a perl5 application to talk to SMTP servers. This
658
+ documentation assumes that you are familiar with the concepts of the
659
+ SMTP protocol described in RFC2821.
660
+ With L<IO::Socket::SSL> installed it also provides support for implicit and
661
+ explicit TLS encryption, i.e. SMTPS or SMTP+STARTTLS.
662
+
663
+ The Net::SMTP class is a subclass of Net::Cmd and (depending on avaibility) of
664
+ IO::Socket::IP, IO::Socket::INET6 or IO::Socket::INET.
665
+
666
+ =head2 Class Methods
667
+
668
+ =over 4
669
+
670
+ =item C<new([$host][, %options])>
671
+
672
+ This is the constructor for a new Net::SMTP object. C<$host> is the
673
+ name of the remote host to which an SMTP connection is required.
674
+
675
+ On failure C<undef> will be returned and C<$@> will contain the reason
676
+ for the failure.
677
+
678
+ C<$host> is optional. If C<$host> is not given then it may instead be
679
+ passed as the C<Host> option described below. If neither is given then
680
+ the C<SMTP_Hosts> specified in C<Net::Config> will be used.
681
+
682
+ C<%options> are passed in a hash like fashion, using key and value pairs.
683
+ Possible options are:
684
+
685
+ B<Hello> - SMTP requires that you identify yourself. This option
686
+ specifies a string to pass as your mail domain. If not given localhost.localdomain
687
+ will be used.
688
+
689
+ B<SendHello> - If false then the EHLO (or HELO) command that is normally sent
690
+ when constructing the object will not be sent. In that case the command will
691
+ have to be sent manually by calling C<hello()> instead.
692
+
693
+ B<Host> - SMTP host to connect to. It may be a single scalar (hostname[:port]),
694
+ as defined for the C<PeerAddr> option in L<IO::Socket::INET>, or a reference to
695
+ an array with hosts to try in turn. The L</host> method will return the value
696
+ which was used to connect to the host.
697
+ Format - C<PeerHost> from L<IO::Socket::INET> new method.
698
+
699
+ B<Port> - port to connect to.
700
+ Default - 25 for plain SMTP and 465 for immediate SSL.
701
+
702
+ B<SSL> - If the connection should be done from start with SSL, contrary to later
703
+ upgrade with C<starttls>.
704
+ You can use SSL arguments as documented in L<IO::Socket::SSL>, but it will
705
+ usually use the right arguments already.
706
+
707
+ B<LocalAddr> and B<LocalPort> - These parameters are passed directly
708
+ to IO::Socket to allow binding the socket to a specific local address and port.
709
+
710
+ B<Domain> - This parameter is passed directly to IO::Socket and makes it
711
+ possible to enforce IPv4 connections even if L<IO::Socket::IP> is used as super
712
+ class. Alternatively B<Family> can be used.
713
+
714
+ B<Timeout> - Maximum time, in seconds, to wait for a response from the
715
+ SMTP server (default: 120)
716
+
717
+ B<ExactAddresses> - If true then all C<$address> arguments must be as
718
+ defined by C<addr-spec> in RFC2822. If not given, or false, then
719
+ Net::SMTP will attempt to extract the address from the value passed.
720
+
721
+ B<Debug> - Enable debugging information
722
+
723
+ Example:
724
+
725
+ $smtp = Net::SMTP->new('mailhost',
726
+ Hello => 'my.mail.domain',
727
+ Timeout => 30,
728
+ Debug => 1,
729
+ );
730
+
731
+ # the same
732
+ $smtp = Net::SMTP->new(
733
+ Host => 'mailhost',
734
+ Hello => 'my.mail.domain',
735
+ Timeout => 30,
736
+ Debug => 1,
737
+ );
738
+
739
+ # the same with direct SSL
740
+ $smtp = Net::SMTP->new('mailhost',
741
+ Hello => 'my.mail.domain',
742
+ Timeout => 30,
743
+ Debug => 1,
744
+ SSL => 1,
745
+ );
746
+
747
+ # Connect to the default server from Net::config
748
+ $smtp = Net::SMTP->new(
749
+ Hello => 'my.mail.domain',
750
+ Timeout => 30,
751
+ );
752
+
753
+ =back
754
+
755
+ =head1 Object Methods
756
+
757
+ Unless otherwise stated all methods return either a I<true> or I<false>
758
+ value, with I<true> meaning that the operation was a success. When a method
759
+ states that it returns a value, failure will be returned as I<undef> or an
760
+ empty list.
761
+
762
+ C<Net::SMTP> inherits from C<Net::Cmd> so methods defined in C<Net::Cmd> may
763
+ be used to send commands to the remote SMTP server in addition to the methods
764
+ documented here.
765
+
766
+ =over 4
767
+
768
+ =item C<banner()>
769
+
770
+ Returns the banner message which the server replied with when the
771
+ initial connection was made.
772
+
773
+ =item C<domain()>
774
+
775
+ Returns the domain that the remote SMTP server identified itself as during
776
+ connection.
777
+
778
+ =item C<hello($domain)>
779
+
780
+ Tell the remote server the mail domain which you are in using the EHLO
781
+ command (or HELO if EHLO fails). Since this method is invoked
782
+ automatically when the Net::SMTP object is constructed the user should
783
+ normally not have to call it manually.
784
+
785
+ =item C<host()>
786
+
787
+ Returns the value used by the constructor, and passed to IO::Socket::INET,
788
+ to connect to the host.
789
+
790
+ =item C<etrn($domain)>
791
+
792
+ Request a queue run for the C<$domain> given.
793
+
794
+ =item C<starttls(%sslargs)>
795
+
796
+ Upgrade existing plain connection to SSL.
797
+ You can use SSL arguments as documented in L<IO::Socket::SSL>, but it will
798
+ usually use the right arguments already.
799
+
800
+ =item C<auth($username, $password)>
801
+
802
+ =item C<auth($sasl)>
803
+
804
+ Attempt SASL authentication. Requires Authen::SASL module. The first form
805
+ constructs a new Authen::SASL object using the given username and password;
806
+ the second form uses the given Authen::SASL object.
807
+
808
+ =item C<mail($address[, %options])>
809
+
810
+ =item C<send($address)>
811
+
812
+ =item C<send_or_mail($address)>
813
+
814
+ =item C<send_and_mail($address)>
815
+
816
+ Send the appropriate command to the server MAIL, SEND, SOML or SAML. C<$address>
817
+ is the address of the sender. This initiates the sending of a message. The
818
+ method C<recipient> should be called for each address that the message is to
819
+ be sent to.
820
+
821
+ The C<mail> method can take some additional ESMTP C<%options> which is passed
822
+ in hash like fashion, using key and value pairs. Possible options are:
823
+
824
+ Size => <bytes>
825
+ Return => "FULL" | "HDRS"
826
+ Bits => "7" | "8" | "binary"
827
+ Transaction => <ADDRESS>
828
+ Envelope => <ENVID> # xtext-encodes its argument
829
+ ENVID => <ENVID> # similar to Envelope, but expects argument encoded
830
+ XVERP => 1
831
+ AUTH => <submitter> # encoded address according to RFC 2554
832
+
833
+ The C<Return> and C<Envelope> parameters are used for DSN (Delivery
834
+ Status Notification).
835
+
836
+ The submitter address in C<AUTH> option is expected to be in a format as
837
+ required by RFC 2554, in an RFC2821-quoted form and xtext-encoded, or <> .
838
+
839
+ =item C<reset()>
840
+
841
+ Reset the status of the server. This may be called after a message has been
842
+ initiated, but before any data has been sent, to cancel the sending of the
843
+ message.
844
+
845
+ =item C<recipient($address[, $address[, ...]][, %options])>
846
+
847
+ Notify the server that the current message should be sent to all of the
848
+ addresses given. Each address is sent as a separate command to the server.
849
+ Should the sending of any address result in a failure then the process is
850
+ aborted and a I<false> value is returned. It is up to the user to call
851
+ C<reset> if they so desire.
852
+
853
+ The C<recipient> method can also pass additional case-sensitive C<%options> as an
854
+ anonymous hash using key and value pairs. Possible options are:
855
+
856
+ Notify => ['NEVER'] or ['SUCCESS','FAILURE','DELAY'] (see below)
857
+ ORcpt => <ORCPT>
858
+ SkipBad => 1 (to ignore bad addresses)
859
+
860
+ If C<SkipBad> is true the C<recipient> will not return an error when a bad
861
+ address is encountered and it will return an array of addresses that did
862
+ succeed.
863
+
864
+ $smtp->recipient($recipient1,$recipient2); # Good
865
+ $smtp->recipient($recipient1,$recipient2, { SkipBad => 1 }); # Good
866
+ $smtp->recipient($recipient1,$recipient2, { Notify => ['FAILURE','DELAY'], SkipBad => 1 }); # Good
867
+ @goodrecips=$smtp->recipient(@recipients, { Notify => ['FAILURE'], SkipBad => 1 }); # Good
868
+ $smtp->recipient("$recipient,$recipient2"); # BAD
869
+
870
+ Notify is used to request Delivery Status Notifications (DSNs), but your
871
+ SMTP/ESMTP service may not respect this request depending upon its version and
872
+ your site's SMTP configuration.
873
+
874
+ Leaving out the Notify option usually defaults an SMTP service to its default
875
+ behavior equivalent to ['FAILURE'] notifications only, but again this may be
876
+ dependent upon your site's SMTP configuration.
877
+
878
+ The NEVER keyword must appear by itself if used within the Notify option and "requests
879
+ that a DSN not be returned to the sender under any conditions."
880
+
881
+ {Notify => ['NEVER']}
882
+
883
+ $smtp->recipient(@recipients, { Notify => ['NEVER'], SkipBad => 1 }); # Good
884
+
885
+ You may use any combination of these three values 'SUCCESS','FAILURE','DELAY' in
886
+ the anonymous array reference as defined by RFC3461 (see
887
+ L<https://www.ietf.org/rfc/rfc3461.txt> for more information. Note: quotations
888
+ in this topic from same.).
889
+
890
+ A Notify parameter of 'SUCCESS' or 'FAILURE' "requests that a DSN be issued on
891
+ successful delivery or delivery failure, respectively."
892
+
893
+ A Notify parameter of 'DELAY' "indicates the sender's willingness to receive
894
+ delayed DSNs. Delayed DSNs may be issued if delivery of a message has been
895
+ delayed for an unusual amount of time (as determined by the Message Transfer
896
+ Agent (MTA) at which the message is delayed), but the final delivery status
897
+ (whether successful or failure) cannot be determined. The absence of the DELAY
898
+ keyword in a NOTIFY parameter requests that a "delayed" DSN NOT be issued under
899
+ any conditions."
900
+
901
+ {Notify => ['SUCCESS','FAILURE','DELAY']}
902
+
903
+ $smtp->recipient(@recipients, { Notify => ['FAILURE','DELAY'], SkipBad => 1 }); # Good
904
+
905
+ ORcpt is also part of the SMTP DSN extension according to RFC3461.
906
+ It is used to pass along the original recipient that the mail was first
907
+ sent to. The machine that generates a DSN will use this address to inform
908
+ the sender, because he can't know if recipients get rewritten by mail servers.
909
+ It is expected to be in a format as required by RFC3461, xtext-encoded.
910
+
911
+ =item C<to($address[, $address[, ...]])>
912
+
913
+ =item C<cc($address[, $address[, ...]])>
914
+
915
+ =item C<bcc($address[, $address[, ...]])>
916
+
917
+ Synonyms for C<recipient>.
918
+
919
+ =item C<data([$data])>
920
+
921
+ Initiate the sending of the data from the current message.
922
+
923
+ C<$data> may be a reference to a list or a list and must be encoded by the
924
+ caller to octets of whatever encoding is required, e.g. by using the Encode
925
+ module's C<encode()> function.
926
+
927
+ If specified the contents of C<$data> and a termination string C<".\r\n"> is
928
+ sent to the server. The result will be true if the data was accepted.
929
+
930
+ If C<$data> is not specified then the result will indicate that the server
931
+ wishes the data to be sent. The data must then be sent using the C<datasend>
932
+ and C<dataend> methods described in L<Net::Cmd>.
933
+
934
+ =item C<bdat($data)>
935
+
936
+ =item C<bdatlast($data)>
937
+
938
+ Use the alternate C<$data> command "BDAT" of the data chunking service extension
939
+ defined in RFC1830 for efficiently sending large MIME messages.
940
+
941
+ =item C<expand($address)>
942
+
943
+ Request the server to expand the given address Returns an array
944
+ which contains the text read from the server.
945
+
946
+ =item C<verify($address)>
947
+
948
+ Verify that C<$address> is a legitimate mailing address.
949
+
950
+ Most sites usually disable this feature in their SMTP service configuration.
951
+ Use "Debug => 1" option under new() to see if disabled.
952
+
953
+ =item C<help([$subject])>
954
+
955
+ Request help text from the server. Returns the text or undef upon failure
956
+
957
+ =item C<quit()>
958
+
959
+ Send the QUIT command to the remote SMTP server and close the socket connection.
960
+
961
+ =item C<can_inet6()>
962
+
963
+ Returns whether we can use IPv6.
964
+
965
+ =item C<can_ssl()>
966
+
967
+ Returns whether we can use SSL.
968
+
969
+ =back
970
+
971
+ =head2 Addresses
972
+
973
+ Net::SMTP attempts to DWIM with addresses that are passed. For
974
+ example an application might extract The From: line from an email
975
+ and pass that to mail(). While this may work, it is not recommended.
976
+ The application should really use a module like L<Mail::Address>
977
+ to extract the mail address and pass that.
978
+
979
+ If C<ExactAddresses> is passed to the constructor, then addresses
980
+ should be a valid rfc2821-quoted address, although Net::SMTP will
981
+ accept the address surrounded by angle brackets.
982
+
983
+ funny user@domain WRONG
984
+ "funny user"@domain RIGHT, recommended
985
+ <"funny user"@domain> OK
986
+
987
+ =head1 EXAMPLES
988
+
989
+ This example prints the mail domain name of the SMTP server known as mailhost:
990
+
991
+ #!/usr/local/bin/perl -w
992
+
993
+ use Net::SMTP;
994
+
995
+ $smtp = Net::SMTP->new('mailhost');
996
+ print $smtp->domain,"\n";
997
+ $smtp->quit;
998
+
999
+ This example sends a small message to the postmaster at the SMTP server
1000
+ known as mailhost:
1001
+
1002
+ #!/usr/local/bin/perl -w
1003
+
1004
+ use Net::SMTP;
1005
+
1006
+ my $smtp = Net::SMTP->new('mailhost');
1007
+
1008
+ $smtp->mail($ENV{USER});
1009
+ if ($smtp->to('postmaster')) {
1010
+ $smtp->data();
1011
+ $smtp->datasend("To: postmaster\n");
1012
+ $smtp->datasend("\n");
1013
+ $smtp->datasend("A simple test message\n");
1014
+ $smtp->dataend();
1015
+ } else {
1016
+ print "Error: ", $smtp->message();
1017
+ }
1018
+
1019
+ $smtp->quit;
1020
+
1021
+ =head1 EXPORTS
1022
+
1023
+ I<None>.
1024
+
1025
+ =head1 KNOWN BUGS
1026
+
1027
+ See L<https://rt.cpan.org/Dist/Display.html?Status=Active&Queue=libnet>.
1028
+
1029
+ =head1 SEE ALSO
1030
+
1031
+ L<Net::Cmd>,
1032
+ L<IO::Socket::SSL>.
1033
+
1034
+ =head1 AUTHOR
1035
+
1036
+ Graham Barr E<lt>L<gbarr@pobox.com|mailto:gbarr@pobox.com>E<gt>.
1037
+
1038
+ Steve Hay E<lt>L<shay@cpan.org|mailto:shay@cpan.org>E<gt> is now maintaining
1039
+ libnet as of version 1.22_02.
1040
+
1041
+ =head1 COPYRIGHT
1042
+
1043
+ Copyright (C) 1995-2004 Graham Barr. All rights reserved.
1044
+
1045
+ Copyright (C) 2013-2016, 2020 Steve Hay. All rights reserved.
1046
+
1047
+ =head1 LICENCE
1048
+
1049
+ This module is free software; you can redistribute it and/or modify it under the
1050
+ same terms as Perl itself, i.e. under the terms of either the GNU General Public
1051
+ License or the Artistic License, as specified in the F<LICENCE> file.
1052
+
1053
+ =head1 VERSION
1054
+
1055
+ Version 3.15
1056
+
1057
+ =head1 DATE
1058
+
1059
+ 20 March 2023
1060
+
1061
+ =head1 HISTORY
1062
+
1063
+ See the F<Changes> file.
1064
+
1065
+ =cut
git/usr/share/perl5/core_perl/Net/Time.pm ADDED
@@ -0,0 +1,203 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Net::Time.pm
2
+ #
3
+ # Copyright (C) 1995-2004 Graham Barr. All rights reserved.
4
+ # Copyright (C) 2014, 2020 Steve Hay. All rights reserved.
5
+ # This module is free software; you can redistribute it and/or modify it under
6
+ # the same terms as Perl itself, i.e. under the terms of either the GNU General
7
+ # Public License or the Artistic License, as specified in the F<LICENCE> file.
8
+
9
+ package Net::Time;
10
+
11
+ use 5.008001;
12
+
13
+ use strict;
14
+ use warnings;
15
+
16
+ use Carp;
17
+ use Exporter;
18
+ use IO::Select;
19
+ use IO::Socket;
20
+ use Net::Config;
21
+
22
+ our @ISA = qw(Exporter);
23
+ our @EXPORT_OK = qw(inet_time inet_daytime);
24
+
25
+ our $VERSION = "3.15";
26
+
27
+ our $TIMEOUT = 120;
28
+
29
+ sub _socket {
30
+ my ($pname, $pnum, $host, $proto, $timeout) = @_;
31
+
32
+ $proto ||= 'udp';
33
+
34
+ my $port = (getservbyname($pname, $proto))[2] || $pnum;
35
+
36
+ my $hosts = defined $host ? [$host] : $NetConfig{$pname . '_hosts'};
37
+
38
+ my $me;
39
+
40
+ foreach my $addr (@$hosts) {
41
+ $me = IO::Socket::INET->new(
42
+ PeerAddr => $addr,
43
+ PeerPort => $port,
44
+ Proto => $proto
45
+ )
46
+ and last;
47
+ }
48
+
49
+ return unless $me;
50
+
51
+ $me->send("\n")
52
+ if $proto eq 'udp';
53
+
54
+ $timeout = $TIMEOUT
55
+ unless defined $timeout;
56
+
57
+ IO::Select->new($me)->can_read($timeout)
58
+ ? $me
59
+ : undef;
60
+ }
61
+
62
+
63
+ sub inet_time {
64
+ my $s = _socket('time', 37, @_) || return;
65
+ my $buf = '';
66
+ my $offset = 0 | 0;
67
+
68
+ return
69
+ unless defined $s->recv($buf, length(pack("N", 0)));
70
+
71
+ # unpack, we | 0 to ensure we have an unsigned
72
+ my $time = (unpack("N", $buf))[0] | 0;
73
+
74
+ # the time protocol return time in seconds since 1900, convert
75
+ # it to a the required format
76
+
77
+ if ($^O eq "MacOS") {
78
+
79
+ # MacOS return seconds since 1904, 1900 was not a leap year.
80
+ $offset = (4 * 31536000) | 0;
81
+ }
82
+ else {
83
+
84
+ # otherwise return seconds since 1972, there were 17 leap years between
85
+ # 1900 and 1972
86
+ $offset = (70 * 31536000 + 17 * 86400) | 0;
87
+ }
88
+
89
+ $time - $offset;
90
+ }
91
+
92
+
93
+ sub inet_daytime {
94
+ my $s = _socket('daytime', 13, @_) || return;
95
+ my $buf = '';
96
+
97
+ defined($s->recv($buf, 1024))
98
+ ? $buf
99
+ : undef;
100
+ }
101
+
102
+ 1;
103
+
104
+ __END__
105
+
106
+ =head1 NAME
107
+
108
+ Net::Time - time and daytime network client interface
109
+
110
+ =head1 SYNOPSIS
111
+
112
+ use Net::Time qw(inet_time inet_daytime);
113
+
114
+ print inet_time(); # use default host from Net::Config
115
+ print inet_time('localhost');
116
+ print inet_time('localhost', 'tcp');
117
+
118
+ print inet_daytime(); # use default host from Net::Config
119
+ print inet_daytime('localhost');
120
+ print inet_daytime('localhost', 'tcp');
121
+
122
+ =head1 DESCRIPTION
123
+
124
+ C<Net::Time> provides subroutines that obtain the time on a remote machine.
125
+
126
+ =head2 Functions
127
+
128
+ =over 4
129
+
130
+ =item C<inet_time([$host[, $protocol[, $timeout]]])>
131
+
132
+ Obtain the time on C<$host>, or some default host if C<$host> is not given
133
+ or not defined, using the protocol as defined in RFC868. The optional
134
+ argument C<$protocol> should define the protocol to use, either C<tcp> or
135
+ C<udp>. The result will be a time value in the same units as returned
136
+ by time() or I<undef> upon failure.
137
+
138
+ =item C<inet_daytime([$host[, $protocol[, $timeout]]])>
139
+
140
+ Obtain the time on C<$host>, or some default host if C<$host> is not given
141
+ or not defined, using the protocol as defined in RFC867. The optional
142
+ argument C<$protocol> should define the protocol to use, either C<tcp> or
143
+ C<udp>. The result will be an ASCII string or I<undef> upon failure.
144
+
145
+ =back
146
+
147
+ =head1 EXPORTS
148
+
149
+ The following symbols are, or can be, exported by this module:
150
+
151
+ =over 4
152
+
153
+ =item Default Exports
154
+
155
+ I<None>.
156
+
157
+ =item Optional Exports
158
+
159
+ C<inet_time>,
160
+ C<inet_daytime>.
161
+
162
+ =item Export Tags
163
+
164
+ I<None>.
165
+
166
+ =back
167
+
168
+ =head1 KNOWN BUGS
169
+
170
+ I<None>.
171
+
172
+ =head1 AUTHOR
173
+
174
+ Graham Barr E<lt>L<gbarr@pobox.com|mailto:gbarr@pobox.com>E<gt>.
175
+
176
+ Steve Hay E<lt>L<shay@cpan.org|mailto:shay@cpan.org>E<gt> is now maintaining
177
+ libnet as of version 1.22_02.
178
+
179
+ =head1 COPYRIGHT
180
+
181
+ Copyright (C) 1995-2004 Graham Barr. All rights reserved.
182
+
183
+ Copyright (C) 2014, 2020 Steve Hay. All rights reserved.
184
+
185
+ =head1 LICENCE
186
+
187
+ This module is free software; you can redistribute it and/or modify it under the
188
+ same terms as Perl itself, i.e. under the terms of either the GNU General Public
189
+ License or the Artistic License, as specified in the F<LICENCE> file.
190
+
191
+ =head1 VERSION
192
+
193
+ Version 3.15
194
+
195
+ =head1 DATE
196
+
197
+ 20 March 2023
198
+
199
+ =head1 HISTORY
200
+
201
+ See the F<Changes> file.
202
+
203
+ =cut
git/usr/share/perl5/core_perl/Net/hostent.pm ADDED
@@ -0,0 +1,148 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package Net::hostent 1.04;
2
+ use v5.38;
3
+
4
+ our (
5
+ $h_name, @h_aliases,
6
+ $h_addrtype, $h_length,
7
+ @h_addr_list, $h_addr
8
+ );
9
+
10
+ use Exporter 'import';
11
+ our @EXPORT = qw(gethostbyname gethostbyaddr gethost);
12
+ our @EXPORT_OK = qw(
13
+ $h_name @h_aliases
14
+ $h_addrtype $h_length
15
+ @h_addr_list $h_addr
16
+ );
17
+ our %EXPORT_TAGS = ( FIELDS => [ @EXPORT_OK, @EXPORT ] );
18
+
19
+ use Class::Struct qw(struct);
20
+ struct 'Net::hostent' => [
21
+ name => '$',
22
+ aliases => '@',
23
+ addrtype => '$',
24
+ 'length' => '$',
25
+ addr_list => '@',
26
+ ];
27
+
28
+ sub addr { shift->addr_list->[0] }
29
+
30
+ sub populate {
31
+ return unless @_;
32
+ my $hob = new();
33
+ $h_name = $hob->[0] = $_[0];
34
+ @h_aliases = @{ $hob->[1] } = split ' ', $_[1];
35
+ $h_addrtype = $hob->[2] = $_[2];
36
+ $h_length = $hob->[3] = $_[3];
37
+ $h_addr = $_[4];
38
+ @h_addr_list = @{ $hob->[4] } = @_[ (4 .. $#_) ];
39
+ return $hob;
40
+ }
41
+
42
+ sub gethostbyname :prototype($) { populate(CORE::gethostbyname(shift)) }
43
+
44
+ sub gethostbyaddr :prototype($;$) {
45
+ my ($addr, $addrtype);
46
+ $addr = shift;
47
+ require Socket unless @_;
48
+ $addrtype = @_ ? shift : Socket::AF_INET();
49
+ populate(CORE::gethostbyaddr($addr, $addrtype))
50
+ }
51
+
52
+ sub gethost :prototype($) {
53
+ my $addr = shift;
54
+ if ($addr =~ /^\d+(?:\.\d+(?:\.\d+(?:\.\d+)?)?)?$/) {
55
+ require Socket;
56
+ &gethostbyaddr(Socket::inet_aton($addr));
57
+ } else {
58
+ &gethostbyname($addr);
59
+ }
60
+ }
61
+
62
+ __END__
63
+
64
+ =head1 NAME
65
+
66
+ Net::hostent - by-name interface to Perl's built-in gethost*() functions
67
+
68
+ =head1 SYNOPSIS
69
+
70
+ use Net::hostent;
71
+
72
+ =head1 DESCRIPTION
73
+
74
+ This module's default exports override the core gethostbyname() and
75
+ gethostbyaddr() functions, replacing them with versions that return
76
+ "Net::hostent" objects. This object has methods that return the similarly
77
+ named structure field name from the C's hostent structure from F<netdb.h>;
78
+ namely name, aliases, addrtype, length, and addr_list. The aliases and
79
+ addr_list methods return array reference, the rest scalars. The addr
80
+ method is equivalent to the zeroth element in the addr_list array
81
+ reference.
82
+
83
+ You may also import all the structure fields directly into your namespace
84
+ as regular variables using the :FIELDS import tag. (Note that this still
85
+ overrides your core functions.) Access these fields as variables named
86
+ with a preceding C<h_>. Thus, C<$host_obj-E<gt>name()> corresponds to
87
+ $h_name if you import the fields. Array references are available as
88
+ regular array variables, so for example C<@{ $host_obj-E<gt>aliases()
89
+ }> would be simply @h_aliases.
90
+
91
+ The gethost() function is a simple front-end that forwards a numeric
92
+ argument to gethostbyaddr() by way of Socket::inet_aton, and the rest
93
+ to gethostbyname().
94
+
95
+ To access this functionality without the core overrides,
96
+ pass the C<use> an empty import list, and then access
97
+ function functions with their full qualified names.
98
+ On the other hand, the built-ins are still available
99
+ via the C<CORE::> pseudo-package.
100
+
101
+ =head1 EXAMPLES
102
+
103
+ use Net::hostent;
104
+ use Socket;
105
+
106
+ @ARGV = ('netscape.com') unless @ARGV;
107
+
108
+ for $host ( @ARGV ) {
109
+
110
+ unless ($h = gethost($host)) {
111
+ warn "$0: no such host: $host\n";
112
+ next;
113
+ }
114
+
115
+ printf "\n%s is %s%s\n",
116
+ $host,
117
+ lc($h->name) eq lc($host) ? "" : "*really* ",
118
+ $h->name;
119
+
120
+ print "\taliases are ", join(", ", @{$h->aliases}), "\n"
121
+ if @{$h->aliases};
122
+
123
+ if ( @{$h->addr_list} > 1 ) {
124
+ my $i;
125
+ for $addr ( @{$h->addr_list} ) {
126
+ printf "\taddr #%d is [%s]\n", $i++, inet_ntoa($addr);
127
+ }
128
+ } else {
129
+ printf "\taddress is [%s]\n", inet_ntoa($h->addr);
130
+ }
131
+
132
+ if ($h = gethostbyaddr($h->addr)) {
133
+ if (lc($h->name) ne lc($host)) {
134
+ printf "\tThat addr reverses to host %s!\n", $h->name;
135
+ $host = $h->name;
136
+ redo;
137
+ }
138
+ }
139
+ }
140
+
141
+ =head1 NOTE
142
+
143
+ While this class is currently implemented using the Class::Struct
144
+ module to build a struct-like class, you shouldn't rely upon this.
145
+
146
+ =head1 AUTHOR
147
+
148
+ Tom Christiansen
git/usr/share/perl5/core_perl/Net/netent.pm ADDED
@@ -0,0 +1,164 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package Net::netent 1.02;
2
+ use v5.38;
3
+
4
+ our (
5
+ $n_name, @n_aliases,
6
+ $n_addrtype, $n_net
7
+ );
8
+
9
+ use Exporter 'import';
10
+ our @EXPORT = qw(getnetbyname getnetbyaddr getnet);
11
+ our @EXPORT_OK = qw(
12
+ $n_name @n_aliases
13
+ $n_addrtype $n_net
14
+ );
15
+ our %EXPORT_TAGS = ( FIELDS => [ @EXPORT_OK, @EXPORT ] );
16
+
17
+ use Class::Struct qw(struct);
18
+ struct 'Net::netent' => [
19
+ name => '$',
20
+ aliases => '@',
21
+ addrtype => '$',
22
+ net => '$',
23
+ ];
24
+
25
+ sub populate {
26
+ return unless @_;
27
+ my $nob = new();
28
+ $n_name = $nob->[0] = $_[0];
29
+ @n_aliases = @{ $nob->[1] } = split ' ', $_[1];
30
+ $n_addrtype = $nob->[2] = $_[2];
31
+ $n_net = $nob->[3] = $_[3];
32
+ return $nob;
33
+ }
34
+
35
+ sub getnetbyname :prototype($) { populate(CORE::getnetbyname(shift)) }
36
+
37
+ sub getnetbyaddr :prototype($;$) {
38
+ my ($net, $addrtype);
39
+ $net = shift;
40
+ require Socket if @_;
41
+ $addrtype = @_ ? shift : Socket::AF_INET();
42
+ populate(CORE::getnetbyaddr($net, $addrtype))
43
+ }
44
+
45
+ sub getnet :prototype($) {
46
+ if ($_[0] =~ /^\d+(?:\.\d+(?:\.\d+(?:\.\d+)?)?)?$/) {
47
+ require Socket;
48
+ &getnetbyaddr(Socket::inet_aton(shift));
49
+ } else {
50
+ &getnetbyname;
51
+ }
52
+ }
53
+
54
+ __END__
55
+
56
+ =head1 NAME
57
+
58
+ Net::netent - by-name interface to Perl's built-in getnet*() functions
59
+
60
+ =head1 SYNOPSIS
61
+
62
+ use Net::netent qw(:FIELDS);
63
+ getnetbyname("loopback") or die "bad net";
64
+ printf "%s is %08X\n", $n_name, $n_net;
65
+
66
+ use Net::netent;
67
+
68
+ $n = getnetbyname("loopback") or die "bad net";
69
+ { # there's gotta be a better way, eh?
70
+ @bytes = unpack("C4", pack("N", $n->net));
71
+ shift @bytes while @bytes && $bytes[0] == 0;
72
+ }
73
+ printf "%s is %08X [%d.%d.%d.%d]\n", $n->name, $n->net, @bytes;
74
+
75
+ =head1 DESCRIPTION
76
+
77
+ This module's default exports override the core getnetbyname() and
78
+ getnetbyaddr() functions, replacing them with versions that return
79
+ "Net::netent" objects. This object has methods that return the similarly
80
+ named structure field name from the C's netent structure from F<netdb.h>;
81
+ namely name, aliases, addrtype, and net. The aliases
82
+ method returns an array reference, the rest scalars.
83
+
84
+ You may also import all the structure fields directly into your namespace
85
+ as regular variables using the :FIELDS import tag. (Note that this still
86
+ overrides your core functions.) Access these fields as variables named
87
+ with a preceding C<n_>. Thus, C<$net_obj-E<gt>name()> corresponds to
88
+ $n_name if you import the fields. Array references are available as
89
+ regular array variables, so for example C<@{ $net_obj-E<gt>aliases()
90
+ }> would be simply @n_aliases.
91
+
92
+ The getnet() function is a simple front-end that forwards a numeric
93
+ argument to getnetbyaddr(), and the rest
94
+ to getnetbyname().
95
+
96
+ To access this functionality without the core overrides,
97
+ pass the C<use> an empty import list, and then access
98
+ function functions with their full qualified names.
99
+ On the other hand, the built-ins are still available
100
+ via the C<CORE::> pseudo-package.
101
+
102
+ =head1 EXAMPLES
103
+
104
+ The getnet() functions do this in the Perl core:
105
+
106
+ sv_setiv(sv, (I32)nent->n_net);
107
+
108
+ The gethost() functions do this in the Perl core:
109
+
110
+ sv_setpvn(sv, hent->h_addr, len);
111
+
112
+ That means that the address comes back in binary for the
113
+ host functions, and as a regular perl integer for the net ones.
114
+ This seems a bug, but here's how to deal with it:
115
+
116
+ use strict;
117
+ use Socket;
118
+ use Net::netent;
119
+
120
+ @ARGV = ('loopback') unless @ARGV;
121
+
122
+ my($n, $net);
123
+
124
+ for $net ( @ARGV ) {
125
+
126
+ unless ($n = getnetbyname($net)) {
127
+ warn "$0: no such net: $net\n";
128
+ next;
129
+ }
130
+
131
+ printf "\n%s is %s%s\n",
132
+ $net,
133
+ lc($n->name) eq lc($net) ? "" : "*really* ",
134
+ $n->name;
135
+
136
+ print "\taliases are ", join(", ", @{$n->aliases}), "\n"
137
+ if @{$n->aliases};
138
+
139
+ # this is stupid; first, why is this not in binary?
140
+ # second, why am i going through these convolutions
141
+ # to make it looks right
142
+ {
143
+ my @a = unpack("C4", pack("N", $n->net));
144
+ shift @a while @a && $a[0] == 0;
145
+ printf "\taddr is %s [%d.%d.%d.%d]\n", $n->net, @a;
146
+ }
147
+
148
+ if ($n = getnetbyaddr($n->net)) {
149
+ if (lc($n->name) ne lc($net)) {
150
+ printf "\tThat addr reverses to net %s!\n", $n->name;
151
+ $net = $n->name;
152
+ redo;
153
+ }
154
+ }
155
+ }
156
+
157
+ =head1 NOTE
158
+
159
+ While this class is currently implemented using the Class::Struct
160
+ module to build a struct-like class, you shouldn't rely upon this.
161
+
162
+ =head1 AUTHOR
163
+
164
+ Tom Christiansen
git/usr/share/perl5/core_perl/Net/protoent.pm ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package Net::protoent 1.03;
2
+ use v5.38;
3
+
4
+ our ( $p_name, @p_aliases, $p_proto );
5
+
6
+ use Exporter 'import';
7
+ our @EXPORT = qw(getprotobyname getprotobynumber getprotoent getproto);
8
+ our @EXPORT_OK = qw( $p_name @p_aliases $p_proto );
9
+ our %EXPORT_TAGS = ( FIELDS => [ @EXPORT_OK, @EXPORT ] );
10
+
11
+ use Class::Struct qw(struct);
12
+ struct 'Net::protoent' => [
13
+ name => '$',
14
+ aliases => '@',
15
+ proto => '$',
16
+ ];
17
+
18
+ sub populate {
19
+ return unless @_;
20
+ my $pob = new();
21
+ $p_name = $pob->[0] = $_[0];
22
+ @p_aliases = @{ $pob->[1] } = split ' ', $_[1];
23
+ $p_proto = $pob->[2] = $_[2];
24
+ return $pob;
25
+ }
26
+
27
+ sub getprotoent :prototype( ) { populate(CORE::getprotoent()) }
28
+ sub getprotobyname :prototype($) { populate(CORE::getprotobyname(shift)) }
29
+ sub getprotobynumber :prototype($) { populate(CORE::getprotobynumber(shift)) }
30
+
31
+ sub getproto :prototype($;$) {
32
+ no strict 'refs';
33
+ return &{'getprotoby' . ($_[0]=~/^\d+$/ ? 'number' : 'name')}(@_);
34
+ }
35
+
36
+ __END__
37
+
38
+ =head1 NAME
39
+
40
+ Net::protoent - by-name interface to Perl's built-in getproto*() functions
41
+
42
+ =head1 SYNOPSIS
43
+
44
+ use Net::protoent;
45
+ my $p = getprotobyname(shift || 'tcp') || die "no proto";
46
+ printf "proto for %s is %d, aliases are %s\n",
47
+ $p->name, $p->proto, "@{$p->aliases}";
48
+
49
+ use Net::protoent qw(:FIELDS);
50
+ getprotobyname(shift || 'tcp') || die "no proto";
51
+ print "proto for $p_name is $p_proto, aliases are @p_aliases\n";
52
+
53
+ =head1 DESCRIPTION
54
+
55
+ This module's default exports override the core getprotoent(),
56
+ getprotobyname(), and getnetbyport() functions, replacing them with
57
+ versions that return "Net::protoent" objects. They take default
58
+ second arguments of "tcp". This object has methods that return the
59
+ similarly named structure field name from the C's protoent structure
60
+ from F<netdb.h>; namely name, aliases, and proto. The aliases method
61
+ returns an array reference, the rest scalars.
62
+
63
+ You may also import all the structure fields directly into your namespace
64
+ as regular variables using the :FIELDS import tag. (Note that this still
65
+ overrides your core functions.) Access these fields as variables named
66
+ with a preceding C<p_>. Thus, C<$proto_obj-E<gt>name()> corresponds to
67
+ $p_name if you import the fields. Array references are available as
68
+ regular array variables, so for example C<@{ $proto_obj-E<gt>aliases()
69
+ }> would be simply @p_aliases.
70
+
71
+ The getproto() function is a simple front-end that forwards a numeric
72
+ argument to getprotobyport(), and the rest to getprotobyname().
73
+
74
+ To access this functionality without the core overrides,
75
+ pass the C<use> an empty import list, and then access
76
+ function functions with their full qualified names.
77
+ On the other hand, the built-ins are still available
78
+ via the C<CORE::> pseudo-package.
79
+
80
+ =head1 NOTE
81
+
82
+ While this class is currently implemented using the Class::Struct
83
+ module to build a struct-like class, you shouldn't rely upon this.
84
+
85
+ =head1 AUTHOR
86
+
87
+ Tom Christiansen
git/usr/share/perl5/core_perl/Net/servent.pm ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package Net::servent 1.04;
2
+ use v5.38;
3
+
4
+ our ( $s_name, @s_aliases, $s_port, $s_proto );
5
+
6
+ use Exporter 'import';
7
+ our @EXPORT = qw(getservbyname getservbyport getservent getserv);
8
+ our @EXPORT_OK = qw( $s_name @s_aliases $s_port $s_proto );
9
+ our %EXPORT_TAGS = ( FIELDS => [ @EXPORT_OK, @EXPORT ] );
10
+
11
+ use Class::Struct qw(struct);
12
+ struct 'Net::servent' => [
13
+ name => '$',
14
+ aliases => '@',
15
+ port => '$',
16
+ proto => '$',
17
+ ];
18
+
19
+ sub populate {
20
+ return unless @_;
21
+ my $sob = new();
22
+ $s_name = $sob->[0] = $_[0];
23
+ @s_aliases = @{ $sob->[1] } = split ' ', $_[1];
24
+ $s_port = $sob->[2] = $_[2];
25
+ $s_proto = $sob->[3] = $_[3];
26
+ return $sob;
27
+ }
28
+
29
+ sub getservent :prototype( ) { populate(CORE::getservent()) }
30
+ sub getservbyname :prototype($;$) { populate(CORE::getservbyname(shift,shift||'tcp')) }
31
+ sub getservbyport :prototype($;$) { populate(CORE::getservbyport(shift,shift||'tcp')) }
32
+
33
+ sub getserv :prototype($;$) {
34
+ no strict 'refs';
35
+ return &{'getservby' . ($_[0]=~/^\d+$/ ? 'port' : 'name')}(@_);
36
+ }
37
+
38
+ __END__
39
+
40
+ =head1 NAME
41
+
42
+ Net::servent - by-name interface to Perl's built-in getserv*() functions
43
+
44
+ =head1 SYNOPSIS
45
+
46
+ use Net::servent;
47
+ my $s = getservbyname(shift || 'ftp') || die "no service";
48
+ printf "port for %s is %s, aliases are %s\n",
49
+ $s->name, $s->port, "@{$s->aliases}";
50
+
51
+ use Net::servent qw(:FIELDS);
52
+ getservbyname(shift || 'ftp') || die "no service";
53
+ print "port for $s_name is $s_port, aliases are @s_aliases\n";
54
+
55
+ =head1 DESCRIPTION
56
+
57
+ This module's default exports override the core getservent(),
58
+ getservbyname(), and
59
+ getnetbyport() functions, replacing them with versions that return
60
+ "Net::servent" objects. They take default second arguments of "tcp". This object has methods that return the similarly
61
+ named structure field name from the C's servent structure from F<netdb.h>;
62
+ namely name, aliases, port, and proto. The aliases
63
+ method returns an array reference, the rest scalars.
64
+
65
+ You may also import all the structure fields directly into your namespace
66
+ as regular variables using the :FIELDS import tag. (Note that this still
67
+ overrides your core functions.) Access these fields as variables named
68
+ with a preceding C<s_>. Thus, C<$serv_obj-E<gt>name()> corresponds to
69
+ $s_name if you import the fields. Array references are available as
70
+ regular array variables, so for example C<@{ $serv_obj-E<gt>aliases()}>
71
+ would be simply @s_aliases.
72
+
73
+ The getserv() function is a simple front-end that forwards a numeric
74
+ argument to getservbyport(), and the rest to getservbyname().
75
+
76
+ To access this functionality without the core overrides,
77
+ pass the C<use> an empty import list, and then access
78
+ function functions with their full qualified names.
79
+ On the other hand, the built-ins are still available
80
+ via the C<CORE::> pseudo-package.
81
+
82
+ =head1 EXAMPLES
83
+
84
+ use Net::servent qw(:FIELDS);
85
+
86
+ while (@ARGV) {
87
+ my ($service, $proto) = ((split m!/!, shift), 'tcp');
88
+ my $valet = getserv($service, $proto);
89
+ unless ($valet) {
90
+ warn "$0: No service: $service/$proto\n"
91
+ next;
92
+ }
93
+ printf "service $service/$proto is port %d\n", $valet->port;
94
+ print "alias are @s_aliases\n" if @s_aliases;
95
+ }
96
+
97
+ =head1 NOTE
98
+
99
+ While this class is currently implemented using the Class::Struct
100
+ module to build a struct-like class, you shouldn't rely upon this.
101
+
102
+ =head1 AUTHOR
103
+
104
+ Tom Christiansen
git/usr/share/perl5/core_perl/Params/Check.pm ADDED
@@ -0,0 +1,695 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package Params::Check;
2
+
3
+ use strict;
4
+
5
+ use Carp qw[carp croak];
6
+ use Locale::Maketext::Simple Style => 'gettext';
7
+
8
+ BEGIN {
9
+ use Exporter ();
10
+ use vars qw[ @ISA $VERSION @EXPORT_OK $VERBOSE $ALLOW_UNKNOWN
11
+ $STRICT_TYPE $STRIP_LEADING_DASHES $NO_DUPLICATES
12
+ $PRESERVE_CASE $ONLY_ALLOW_DEFINED $WARNINGS_FATAL
13
+ $SANITY_CHECK_TEMPLATE $CALLER_DEPTH $_ERROR_STRING
14
+ ];
15
+
16
+ @ISA = qw[ Exporter ];
17
+ @EXPORT_OK = qw[check allow last_error];
18
+
19
+ $VERSION = '0.38';
20
+ $VERBOSE = $^W ? 1 : 0;
21
+ $NO_DUPLICATES = 0;
22
+ $STRIP_LEADING_DASHES = 0;
23
+ $STRICT_TYPE = 0;
24
+ $ALLOW_UNKNOWN = 0;
25
+ $PRESERVE_CASE = 0;
26
+ $ONLY_ALLOW_DEFINED = 0;
27
+ $SANITY_CHECK_TEMPLATE = 1;
28
+ $WARNINGS_FATAL = 0;
29
+ $CALLER_DEPTH = 0;
30
+ }
31
+
32
+ my %known_keys = map { $_ => 1 }
33
+ qw| required allow default strict_type no_override
34
+ store defined |;
35
+
36
+ =pod
37
+
38
+ =head1 NAME
39
+
40
+ Params::Check - A generic input parsing/checking mechanism.
41
+
42
+ =head1 SYNOPSIS
43
+
44
+ use Params::Check qw[check allow last_error];
45
+
46
+ sub fill_personal_info {
47
+ my %hash = @_;
48
+ my $x;
49
+
50
+ my $tmpl = {
51
+ firstname => { required => 1, defined => 1 },
52
+ lastname => { required => 1, store => \$x },
53
+ gender => { required => 1,
54
+ allow => [qr/M/i, qr/F/i],
55
+ },
56
+ married => { allow => [0,1] },
57
+ age => { default => 21,
58
+ allow => qr/^\d+$/,
59
+ },
60
+
61
+ phone => { allow => [ sub { return 1 if /$valid_re/ },
62
+ '1-800-PERL' ]
63
+ },
64
+ id_list => { default => [],
65
+ strict_type => 1
66
+ },
67
+ employer => { default => 'NSA', no_override => 1 },
68
+ };
69
+
70
+ ### check() returns a hashref of parsed args on success ###
71
+ my $parsed_args = check( $tmpl, \%hash, $VERBOSE )
72
+ or die qw[Could not parse arguments!];
73
+
74
+ ... other code here ...
75
+ }
76
+
77
+ my $ok = allow( $colour, [qw|blue green yellow|] );
78
+
79
+ my $error = Params::Check::last_error();
80
+
81
+
82
+ =head1 DESCRIPTION
83
+
84
+ Params::Check is a generic input parsing/checking mechanism.
85
+
86
+ It allows you to validate input via a template. The only requirement
87
+ is that the arguments must be named.
88
+
89
+ Params::Check can do the following things for you:
90
+
91
+ =over 4
92
+
93
+ =item *
94
+
95
+ Convert all keys to lowercase
96
+
97
+ =item *
98
+
99
+ Check if all required arguments have been provided
100
+
101
+ =item *
102
+
103
+ Set arguments that have not been provided to the default
104
+
105
+ =item *
106
+
107
+ Weed out arguments that are not supported and warn about them to the
108
+ user
109
+
110
+ =item *
111
+
112
+ Validate the arguments given by the user based on strings, regexes,
113
+ lists or even subroutines
114
+
115
+ =item *
116
+
117
+ Enforce type integrity if required
118
+
119
+ =back
120
+
121
+ Most of Params::Check's power comes from its template, which we'll
122
+ discuss below:
123
+
124
+ =head1 Template
125
+
126
+ As you can see in the synopsis, based on your template, the arguments
127
+ provided will be validated.
128
+
129
+ The template can take a different set of rules per key that is used.
130
+
131
+ The following rules are available:
132
+
133
+ =over 4
134
+
135
+ =item default
136
+
137
+ This is the default value if none was provided by the user.
138
+ This is also the type C<strict_type> will look at when checking type
139
+ integrity (see below).
140
+
141
+ =item required
142
+
143
+ A boolean flag that indicates if this argument was a required
144
+ argument. If marked as required and not provided, check() will fail.
145
+
146
+ =item strict_type
147
+
148
+ This does a C<ref()> check on the argument provided. The C<ref> of the
149
+ argument must be the same as the C<ref> of the default value for this
150
+ check to pass.
151
+
152
+ This is very useful if you insist on taking an array reference as
153
+ argument for example.
154
+
155
+ =item defined
156
+
157
+ If this template key is true, enforces that if this key is provided by
158
+ user input, its value is C<defined>. This just means that the user is
159
+ not allowed to pass C<undef> as a value for this key and is equivalent
160
+ to:
161
+ allow => sub { defined $_[0] && OTHER TESTS }
162
+
163
+ =item no_override
164
+
165
+ This allows you to specify C<constants> in your template. ie, they
166
+ keys that are not allowed to be altered by the user. It pretty much
167
+ allows you to keep all your C<configurable> data in one place; the
168
+ C<Params::Check> template.
169
+
170
+ =item store
171
+
172
+ This allows you to pass a reference to a scalar, in which the data
173
+ will be stored:
174
+
175
+ my $x;
176
+ my $args = check(foo => { default => 1, store => \$x }, $input);
177
+
178
+ This is basically shorthand for saying:
179
+
180
+ my $args = check( { foo => { default => 1 }, $input );
181
+ my $x = $args->{foo};
182
+
183
+ You can alter the global variable $Params::Check::NO_DUPLICATES to
184
+ control whether the C<store>'d key will still be present in your
185
+ result set. See the L<Global Variables> section below.
186
+
187
+ =item allow
188
+
189
+ A set of criteria used to validate a particular piece of data if it
190
+ has to adhere to particular rules.
191
+
192
+ See the C<allow()> function for details.
193
+
194
+ =back
195
+
196
+ =head1 Functions
197
+
198
+ =head2 check( \%tmpl, \%args, [$verbose] );
199
+
200
+ This function is not exported by default, so you'll have to ask for it
201
+ via:
202
+
203
+ use Params::Check qw[check];
204
+
205
+ or use its fully qualified name instead.
206
+
207
+ C<check> takes a list of arguments, as follows:
208
+
209
+ =over 4
210
+
211
+ =item Template
212
+
213
+ This is a hash reference which contains a template as explained in the
214
+ C<SYNOPSIS> and C<Template> section.
215
+
216
+ =item Arguments
217
+
218
+ This is a reference to a hash of named arguments which need checking.
219
+
220
+ =item Verbose
221
+
222
+ A boolean to indicate whether C<check> should be verbose and warn
223
+ about what went wrong in a check or not.
224
+
225
+ You can enable this program wide by setting the package variable
226
+ C<$Params::Check::VERBOSE> to a true value. For details, see the
227
+ section on C<Global Variables> below.
228
+
229
+ =back
230
+
231
+ C<check> will return when it fails, or a hashref with lowercase
232
+ keys of parsed arguments when it succeeds.
233
+
234
+ So a typical call to check would look like this:
235
+
236
+ my $parsed = check( \%template, \%arguments, $VERBOSE )
237
+ or warn q[Arguments could not be parsed!];
238
+
239
+ A lot of the behaviour of C<check()> can be altered by setting
240
+ package variables. See the section on C<Global Variables> for details
241
+ on this.
242
+
243
+ =cut
244
+
245
+ sub check {
246
+ my ($utmpl, $href, $verbose) = @_;
247
+
248
+ ### clear the current error string ###
249
+ _clear_error();
250
+
251
+ ### did we get the arguments we need? ###
252
+ if ( !$utmpl or !$href ) {
253
+ _store_error(loc('check() expects two arguments'));
254
+ return unless $WARNINGS_FATAL;
255
+ croak(__PACKAGE__->last_error);
256
+ }
257
+
258
+ ### sensible defaults ###
259
+ $verbose ||= $VERBOSE || 0;
260
+
261
+ ### XXX what type of template is it? ###
262
+ ### { key => { } } ?
263
+ #if (ref $args eq 'HASH') {
264
+ # 1;
265
+ #}
266
+
267
+ ### clean up the template ###
268
+ my $args;
269
+
270
+ ### don't even bother to loop, if there's nothing to clean up ###
271
+ if( $PRESERVE_CASE and !$STRIP_LEADING_DASHES ) {
272
+ $args = $href;
273
+ } else {
274
+ ### keys are not aliased ###
275
+ for my $key (keys %$href) {
276
+ my $org = $key;
277
+ $key = lc $key unless $PRESERVE_CASE;
278
+ $key =~ s/^-// if $STRIP_LEADING_DASHES;
279
+ $args->{$key} = $href->{$org};
280
+ }
281
+ }
282
+
283
+ my %defs;
284
+
285
+ ### which template entries have a 'store' member
286
+ my @want_store;
287
+
288
+ ### sanity check + defaults + required keys set? ###
289
+ my $fail;
290
+ for my $key (keys %$utmpl) {
291
+ my $tmpl = $utmpl->{$key};
292
+
293
+ ### check if required keys are provided
294
+ ### keys are now lower cased, unless preserve case was enabled
295
+ ### at which point, the utmpl keys must match, but that's the users
296
+ ### problem.
297
+ if( $tmpl->{'required'} and not exists $args->{$key} ) {
298
+ _store_error(
299
+ loc(q|Required option '%1' is not provided for %2 by %3|,
300
+ $key, _who_was_it(), _who_was_it(1)), $verbose );
301
+
302
+ ### mark the error ###
303
+ $fail++;
304
+ next;
305
+ }
306
+
307
+ ### next, set the default, make sure the key exists in %defs ###
308
+ $defs{$key} = $tmpl->{'default'}
309
+ if exists $tmpl->{'default'};
310
+
311
+ if( $SANITY_CHECK_TEMPLATE ) {
312
+ ### last, check if they provided any weird template keys
313
+ ### -- do this last so we don't always execute this code.
314
+ ### just a small optimization.
315
+ map { _store_error(
316
+ loc(q|Template type '%1' not supported [at key '%2']|,
317
+ $_, $key), 1, 0 );
318
+ } grep {
319
+ not $known_keys{$_}
320
+ } keys %$tmpl;
321
+
322
+ ### make sure you passed a ref, otherwise, complain about it!
323
+ if ( exists $tmpl->{'store'} ) {
324
+ _store_error( loc(
325
+ q|Store variable for '%1' is not a reference!|, $key
326
+ ), 1, 0 ) unless ref $tmpl->{'store'};
327
+ }
328
+ }
329
+
330
+ push @want_store, $key if $tmpl->{'store'};
331
+ }
332
+
333
+ ### errors found ###
334
+ return if $fail;
335
+
336
+ ### flag to see if anything went wrong ###
337
+ my $wrong;
338
+
339
+ ### flag to see if we warned for anything, needed for warnings_fatal
340
+ my $warned;
341
+
342
+ for my $key (keys %$args) {
343
+ my $arg = $args->{$key};
344
+
345
+ ### you gave us this key, but it's not in the template ###
346
+ unless( $utmpl->{$key} ) {
347
+
348
+ ### but we'll allow it anyway ###
349
+ if( $ALLOW_UNKNOWN ) {
350
+ $defs{$key} = $arg;
351
+
352
+ ### warn about the error ###
353
+ } else {
354
+ _store_error(
355
+ loc("Key '%1' is not a valid key for %2 provided by %3",
356
+ $key, _who_was_it(), _who_was_it(1)), $verbose);
357
+ $warned ||= 1;
358
+ }
359
+ next;
360
+ }
361
+
362
+ ### copy of this keys template instructions, to save derefs ###
363
+ my %tmpl = %{$utmpl->{$key}};
364
+
365
+ ### check if you're even allowed to override this key ###
366
+ if( $tmpl{'no_override'} ) {
367
+ _store_error(
368
+ loc(q[You are not allowed to override key '%1'].
369
+ q[for %2 from %3], $key, _who_was_it(), _who_was_it(1)),
370
+ $verbose
371
+ );
372
+ $warned ||= 1;
373
+ next;
374
+ }
375
+
376
+ ### check if you were supposed to provide defined() values ###
377
+ if( ($tmpl{'defined'} || $ONLY_ALLOW_DEFINED) and not defined $arg ) {
378
+ _store_error(loc(q|Key '%1' must be defined when passed|, $key),
379
+ $verbose );
380
+ $wrong ||= 1;
381
+ next;
382
+ }
383
+
384
+ ### check if they should be of a strict type, and if it is ###
385
+ if( ($tmpl{'strict_type'} || $STRICT_TYPE) and
386
+ (ref $arg ne ref $tmpl{'default'})
387
+ ) {
388
+ _store_error(loc(q|Key '%1' needs to be of type '%2'|,
389
+ $key, ref $tmpl{'default'} || 'SCALAR'), $verbose );
390
+ $wrong ||= 1;
391
+ next;
392
+ }
393
+
394
+ ### check if we have an allow handler, to validate against ###
395
+ ### allow() will report its own errors ###
396
+ if( exists $tmpl{'allow'} and not do {
397
+ local $_ERROR_STRING;
398
+ allow( $arg, $tmpl{'allow'} )
399
+ }
400
+ ) {
401
+ ### stringify the value in the error report -- we don't want dumps
402
+ ### of objects, but we do want to see *roughly* what we passed
403
+ _store_error(loc(q|Key '%1' (%2) is of invalid type for '%3' |.
404
+ q|provided by %4|,
405
+ $key, "$arg", _who_was_it(),
406
+ _who_was_it(1)), $verbose);
407
+ $wrong ||= 1;
408
+ next;
409
+ }
410
+
411
+ ### we got here, then all must be OK ###
412
+ $defs{$key} = $arg;
413
+
414
+ }
415
+
416
+ ### croak with the collected errors if there were errors and
417
+ ### we have the fatal flag toggled.
418
+ croak(__PACKAGE__->last_error) if ($wrong || $warned) && $WARNINGS_FATAL;
419
+
420
+ ### done with our loop... if $wrong is set, something went wrong
421
+ ### and the user is already informed, just return...
422
+ return if $wrong;
423
+
424
+ ### check if we need to store any of the keys ###
425
+ ### can't do it before, because something may go wrong later,
426
+ ### leaving the user with a few set variables
427
+ for my $key (@want_store) {
428
+ next unless exists $defs{$key};
429
+ my $ref = $utmpl->{$key}{'store'};
430
+ $$ref = $NO_DUPLICATES ? delete $defs{$key} : $defs{$key};
431
+ }
432
+
433
+ return \%defs;
434
+ }
435
+
436
+ =head2 allow( $test_me, \@criteria );
437
+
438
+ The function that handles the C<allow> key in the template is also
439
+ available for independent use.
440
+
441
+ The function takes as first argument a key to test against, and
442
+ as second argument any form of criteria that are also allowed by
443
+ the C<allow> key in the template.
444
+
445
+ You can use the following types of values for allow:
446
+
447
+ =over 4
448
+
449
+ =item string
450
+
451
+ The provided argument MUST be equal to the string for the validation
452
+ to pass.
453
+
454
+ =item regexp
455
+
456
+ The provided argument MUST match the regular expression for the
457
+ validation to pass.
458
+
459
+ =item subroutine
460
+
461
+ The provided subroutine MUST return true in order for the validation
462
+ to pass and the argument accepted.
463
+
464
+ (This is particularly useful for more complicated data).
465
+
466
+ =item array ref
467
+
468
+ The provided argument MUST equal one of the elements of the array
469
+ ref for the validation to pass. An array ref can hold all the above
470
+ values.
471
+
472
+ =back
473
+
474
+ It returns true if the key matched the criteria, or false otherwise.
475
+
476
+ =cut
477
+
478
+ sub allow {
479
+ ### use $_[0] and $_[1] since this is hot code... ###
480
+ #my ($val, $ref) = @_;
481
+
482
+ ### it's a regexp ###
483
+ if( ref $_[1] eq 'Regexp' ) {
484
+ local $^W; # silence warnings if $val is undef #
485
+ return if $_[0] !~ /$_[1]/;
486
+
487
+ ### it's a sub ###
488
+ } elsif ( ref $_[1] eq 'CODE' ) {
489
+ return unless $_[1]->( $_[0] );
490
+
491
+ ### it's an array ###
492
+ } elsif ( ref $_[1] eq 'ARRAY' ) {
493
+
494
+ ### loop over the elements, see if one of them says the
495
+ ### value is OK
496
+ ### also, short-circuit when possible
497
+ for ( @{$_[1]} ) {
498
+ return 1 if allow( $_[0], $_ );
499
+ }
500
+
501
+ return;
502
+
503
+ ### fall back to a simple, but safe 'eq' ###
504
+ } else {
505
+ return unless _safe_eq( $_[0], $_[1] );
506
+ }
507
+
508
+ ### we got here, no failures ###
509
+ return 1;
510
+ }
511
+
512
+ ### helper functions ###
513
+
514
+ sub _safe_eq {
515
+ ### only do a straight 'eq' if they're both defined ###
516
+ return defined($_[0]) && defined($_[1])
517
+ ? $_[0] eq $_[1]
518
+ : defined($_[0]) eq defined($_[1]);
519
+ }
520
+
521
+ sub _who_was_it {
522
+ my $level = $_[0] || 0;
523
+
524
+ return (caller(2 + $CALLER_DEPTH + $level))[3] || 'ANON'
525
+ }
526
+
527
+ =head2 last_error()
528
+
529
+ Returns a string containing all warnings and errors reported during
530
+ the last time C<check> was called.
531
+
532
+ This is useful if you want to report then some other way than
533
+ C<carp>'ing when the verbose flag is on.
534
+
535
+ It is exported upon request.
536
+
537
+ =cut
538
+
539
+ { $_ERROR_STRING = '';
540
+
541
+ sub _store_error {
542
+ my($err, $verbose, $offset) = @_[0..2];
543
+ $verbose ||= 0;
544
+ $offset ||= 0;
545
+ my $level = 1 + $offset;
546
+
547
+ local $Carp::CarpLevel = $level;
548
+
549
+ carp $err if $verbose;
550
+
551
+ $_ERROR_STRING .= $err . "\n";
552
+ }
553
+
554
+ sub _clear_error {
555
+ $_ERROR_STRING = '';
556
+ }
557
+
558
+ sub last_error { $_ERROR_STRING }
559
+ }
560
+
561
+ 1;
562
+
563
+ =head1 Global Variables
564
+
565
+ The behaviour of Params::Check can be altered by changing the
566
+ following global variables:
567
+
568
+ =head2 $Params::Check::VERBOSE
569
+
570
+ This controls whether Params::Check will issue warnings and
571
+ explanations as to why certain things may have failed.
572
+ If you set it to 0, Params::Check will not output any warnings.
573
+
574
+ The default is 1 when L<warnings> are enabled, 0 otherwise;
575
+
576
+ =head2 $Params::Check::STRICT_TYPE
577
+
578
+ This works like the C<strict_type> option you can pass to C<check>,
579
+ which will turn on C<strict_type> globally for all calls to C<check>.
580
+
581
+ The default is 0;
582
+
583
+ =head2 $Params::Check::ALLOW_UNKNOWN
584
+
585
+ If you set this flag, unknown options will still be present in the
586
+ return value, rather than filtered out. This is useful if your
587
+ subroutine is only interested in a few arguments, and wants to pass
588
+ the rest on blindly to perhaps another subroutine.
589
+
590
+ The default is 0;
591
+
592
+ =head2 $Params::Check::STRIP_LEADING_DASHES
593
+
594
+ If you set this flag, all keys passed in the following manner:
595
+
596
+ function( -key => 'val' );
597
+
598
+ will have their leading dashes stripped.
599
+
600
+ =head2 $Params::Check::NO_DUPLICATES
601
+
602
+ If set to true, all keys in the template that are marked as to be
603
+ stored in a scalar, will also be removed from the result set.
604
+
605
+ Default is false, meaning that when you use C<store> as a template
606
+ key, C<check> will put it both in the scalar you supplied, as well as
607
+ in the hashref it returns.
608
+
609
+ =head2 $Params::Check::PRESERVE_CASE
610
+
611
+ If set to true, L<Params::Check> will no longer convert all keys from
612
+ the user input to lowercase, but instead expect them to be in the
613
+ case the template provided. This is useful when you want to use
614
+ similar keys with different casing in your templates.
615
+
616
+ Understand that this removes the case-insensitivity feature of this
617
+ module.
618
+
619
+ Default is 0;
620
+
621
+ =head2 $Params::Check::ONLY_ALLOW_DEFINED
622
+
623
+ If set to true, L<Params::Check> will require all values passed to be
624
+ C<defined>. If you wish to enable this on a 'per key' basis, use the
625
+ template option C<defined> instead.
626
+
627
+ Default is 0;
628
+
629
+ =head2 $Params::Check::SANITY_CHECK_TEMPLATE
630
+
631
+ If set to true, L<Params::Check> will sanity check templates, validating
632
+ for errors and unknown keys. Although very useful for debugging, this
633
+ can be somewhat slow in hot-code and large loops.
634
+
635
+ To disable this check, set this variable to C<false>.
636
+
637
+ Default is 1;
638
+
639
+ =head2 $Params::Check::WARNINGS_FATAL
640
+
641
+ If set to true, L<Params::Check> will C<croak> when an error during
642
+ template validation occurs, rather than return C<false>.
643
+
644
+ Default is 0;
645
+
646
+ =head2 $Params::Check::CALLER_DEPTH
647
+
648
+ This global modifies the argument given to C<caller()> by
649
+ C<Params::Check::check()> and is useful if you have a custom wrapper
650
+ function around C<Params::Check::check()>. The value must be an
651
+ integer, indicating the number of wrapper functions inserted between
652
+ the real function call and C<Params::Check::check()>.
653
+
654
+ Example wrapper function, using a custom stacktrace:
655
+
656
+ sub check {
657
+ my ($template, $args_in) = @_;
658
+
659
+ local $Params::Check::WARNINGS_FATAL = 1;
660
+ local $Params::Check::CALLER_DEPTH = $Params::Check::CALLER_DEPTH + 1;
661
+ my $args_out = Params::Check::check($template, $args_in);
662
+
663
+ my_stacktrace(Params::Check::last_error) unless $args_out;
664
+
665
+ return $args_out;
666
+ }
667
+
668
+ Default is 0;
669
+
670
+ =head1 Acknowledgements
671
+
672
+ Thanks to Richard Soderberg for his performance improvements.
673
+
674
+ =head1 BUG REPORTS
675
+
676
+ Please report bugs or other issues to E<lt>bug-params-check@rt.cpan.orgE<gt>.
677
+
678
+ =head1 AUTHOR
679
+
680
+ This module by Jos Boumans E<lt>kane@cpan.orgE<gt>.
681
+
682
+ =head1 COPYRIGHT
683
+
684
+ This library is free software; you may redistribute and/or modify it
685
+ under the same terms as Perl itself.
686
+
687
+
688
+ =cut
689
+
690
+ # Local variables:
691
+ # c-indentation-style: bsd
692
+ # c-basic-offset: 4
693
+ # indent-tabs-mode: nil
694
+ # End:
695
+ # vim: expandtab shiftwidth=4:
git/usr/share/perl5/core_perl/Perl/OSType.pm ADDED
@@ -0,0 +1,225 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ use strict;
2
+ use warnings;
3
+
4
+ package Perl::OSType;
5
+ # ABSTRACT: Map Perl operating system names to generic types
6
+
7
+ our $VERSION = '1.010';
8
+
9
+ require Exporter;
10
+ our @ISA = qw(Exporter);
11
+
12
+ our %EXPORT_TAGS = ( all => [qw( os_type is_os_type )] );
13
+
14
+ our @EXPORT_OK = @{ $EXPORT_TAGS{all} };
15
+
16
+ # originally taken from Module::Build by Ken Williams et al.
17
+ my %OSTYPES = qw(
18
+ aix Unix
19
+ bsdos Unix
20
+ beos Unix
21
+ bitrig Unix
22
+ dgux Unix
23
+ dragonfly Unix
24
+ dynixptx Unix
25
+ freebsd Unix
26
+ linux Unix
27
+ haiku Unix
28
+ hpux Unix
29
+ iphoneos Unix
30
+ irix Unix
31
+ darwin Unix
32
+ machten Unix
33
+ midnightbsd Unix
34
+ minix Unix
35
+ mirbsd Unix
36
+ next Unix
37
+ openbsd Unix
38
+ netbsd Unix
39
+ dec_osf Unix
40
+ nto Unix
41
+ svr4 Unix
42
+ svr5 Unix
43
+ sco Unix
44
+ sco_sv Unix
45
+ unicos Unix
46
+ unicosmk Unix
47
+ solaris Unix
48
+ sunos Unix
49
+ cygwin Unix
50
+ msys Unix
51
+ os2 Unix
52
+ interix Unix
53
+ gnu Unix
54
+ gnukfreebsd Unix
55
+ nto Unix
56
+ qnx Unix
57
+ android Unix
58
+
59
+ dos Windows
60
+ MSWin32 Windows
61
+
62
+ os390 EBCDIC
63
+ os400 EBCDIC
64
+ posix-bc EBCDIC
65
+ vmesa EBCDIC
66
+
67
+ MacOS MacOS
68
+ VMS VMS
69
+ vos VOS
70
+ riscos RiscOS
71
+ amigaos Amiga
72
+ mpeix MPEiX
73
+ );
74
+
75
+ sub os_type {
76
+ my ($os) = @_;
77
+ $os = $^O unless defined $os;
78
+ return $OSTYPES{$os} || q{};
79
+ }
80
+
81
+ sub is_os_type {
82
+ my ( $type, $os ) = @_;
83
+ return unless $type;
84
+ $os = $^O unless defined $os;
85
+ return os_type($os) eq $type;
86
+ }
87
+
88
+ 1;
89
+
90
+ =pod
91
+
92
+ =encoding UTF-8
93
+
94
+ =head1 NAME
95
+
96
+ Perl::OSType - Map Perl operating system names to generic types
97
+
98
+ =head1 VERSION
99
+
100
+ version 1.010
101
+
102
+ =head1 SYNOPSIS
103
+
104
+ use Perl::OSType ':all';
105
+
106
+ $current_type = os_type();
107
+ $other_type = os_type('dragonfly'); # gives 'Unix'
108
+
109
+ =head1 DESCRIPTION
110
+
111
+ Modules that provide OS-specific behaviors often need to know if
112
+ the current operating system matches a more generic type of
113
+ operating systems. For example, 'linux' is a type of 'Unix' operating system
114
+ and so is 'freebsd'.
115
+
116
+ This module provides a mapping between an operating system name as given by
117
+ C<$^O> and a more generic type. The initial version is based on the OS type
118
+ mappings provided in L<Module::Build> and L<ExtUtils::CBuilder>. (Thus,
119
+ Microsoft operating systems are given the type 'Windows' rather than 'Win32'.)
120
+
121
+ =head1 USAGE
122
+
123
+ No functions are exported by default. The export tag ":all" will export
124
+ all functions listed below.
125
+
126
+ =head2 os_type()
127
+
128
+ $os_type = os_type();
129
+ $os_type = os_type('MSWin32');
130
+
131
+ Returns a single, generic OS type for a given operating system name. With no
132
+ arguments, returns the OS type for the current value of C<$^O>. If the
133
+ operating system is not recognized, the function will return the empty string.
134
+
135
+ =head2 is_os_type()
136
+
137
+ $is_windows = is_os_type('Windows');
138
+ $is_unix = is_os_type('Unix', 'dragonfly');
139
+
140
+ Given an OS type and OS name, returns true or false if the OS name is of the
141
+ given type. As with C<os_type>, it will use the current operating system as a
142
+ default if no OS name is provided.
143
+
144
+ =head1 SEE ALSO
145
+
146
+ =over 4
147
+
148
+ =item *
149
+
150
+ L<Devel::CheckOS>
151
+
152
+ =back
153
+
154
+ =for :stopwords cpan testmatrix url annocpan anno bugtracker rt cpants kwalitee diff irc mailto metadata placeholders metacpan
155
+
156
+ =head1 SUPPORT
157
+
158
+ =head2 Bugs / Feature Requests
159
+
160
+ Please report any bugs or feature requests through the issue tracker
161
+ at L<https://github.com/Perl-Toolchain-Gang/Perl-OSType/issues>.
162
+ You will be notified automatically of any progress on your issue.
163
+
164
+ =head2 Source Code
165
+
166
+ This is open source software. The code repository is available for
167
+ public review and contribution under the terms of the license.
168
+
169
+ L<https://github.com/Perl-Toolchain-Gang/Perl-OSType>
170
+
171
+ git clone https://github.com/Perl-Toolchain-Gang/Perl-OSType.git
172
+
173
+ =head1 AUTHOR
174
+
175
+ David Golden <dagolden@cpan.org>
176
+
177
+ =head1 CONTRIBUTORS
178
+
179
+ =for stopwords Chris 'BinGOs' Williams David Golden Graham Ollis Jonas B. Nielsen Owain G. Ainsworth Paul Green Piotr Roszatycki
180
+
181
+ =over 4
182
+
183
+ =item *
184
+
185
+ Chris 'BinGOs' Williams <chris@bingosnet.co.uk>
186
+
187
+ =item *
188
+
189
+ David Golden <xdg@xdg.me>
190
+
191
+ =item *
192
+
193
+ Graham Ollis <plicease@cpan.org>
194
+
195
+ =item *
196
+
197
+ Jonas B. Nielsen <jonasbn@hoarfrost.local>
198
+
199
+ =item *
200
+
201
+ Owain G. Ainsworth <oga@nicotinebsd.org>
202
+
203
+ =item *
204
+
205
+ Paul Green <Paul.Green@stratus.com>
206
+
207
+ =item *
208
+
209
+ Piotr Roszatycki <piotr.roszatycki@gmail.com>
210
+
211
+ =back
212
+
213
+ =head1 COPYRIGHT AND LICENSE
214
+
215
+ This software is copyright (c) 2016 by David Golden.
216
+
217
+ This is free software; you can redistribute it and/or modify it under
218
+ the same terms as the Perl 5 programming language system itself.
219
+
220
+ =cut
221
+
222
+ __END__
223
+
224
+
225
+ # vim: ts=4 sts=4 sw=4 et:
git/usr/share/perl5/core_perl/PerlIO/scalar.pm ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package PerlIO::scalar;
2
+ our $VERSION = '0.32';
3
+ 1;
4
+ __END__
5
+
6
+ =head1 NAME
7
+
8
+ PerlIO::scalar - in-memory IO, scalar IO
9
+
10
+ =head1 SYNOPSIS
11
+
12
+ my $scalar = '';
13
+ ...
14
+ open my $fh, "<", \$scalar or die;
15
+ open my $fh, ">", \$scalar or die;
16
+ open my $fh, ">>", \$scalar or die;
17
+
18
+ or
19
+
20
+ my $scalar = '';
21
+ ...
22
+ open my $fh, "<:scalar", \$scalar or die;
23
+ open my $fh, ">:scalar", \$scalar or die;
24
+ open my $fh, ">>:scalar", \$scalar or die;
25
+
26
+ =head1 DESCRIPTION
27
+
28
+ A filehandle is opened but the file operations are performed "in-memory"
29
+ on a scalar variable. All the normal file operations can be performed
30
+ on the handle. The scalar is considered a stream of bytes. Currently
31
+ fileno($fh) returns -1.
32
+
33
+ Attempting to open a read-only scalar for writing will fail, and if
34
+ warnings are enabled, produce a warning.
35
+
36
+ =head1 IMPLEMENTATION NOTE
37
+
38
+ C<PerlIO::scalar> only exists as a stub. One does not need to explicitly
39
+ C<use PerlIO::scalar>.
40
+
41
+ =cut
git/usr/share/perl5/core_perl/Search/Dict.pm ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package Search::Dict;
2
+ use strict;
3
+ use Exporter;
4
+
5
+ BEGIN {
6
+ if ("$]" >= 5.015008) {
7
+ require feature;
8
+ 'feature'->import('fc'); # string avoids warning on old Perls <sigh>
9
+ } else {
10
+ # ($) prototype, not (_), for perl 5.8 compatibility, just in case
11
+ *fc = sub ($) { lc $_[0] };
12
+ }
13
+ }
14
+
15
+ our $VERSION = '1.08';
16
+ our @ISA = qw(Exporter);
17
+ our @EXPORT = qw(look);
18
+
19
+ =head1 NAME
20
+
21
+ Search::Dict - look - search for key in dictionary file
22
+
23
+ =head1 SYNOPSIS
24
+
25
+ use Search::Dict;
26
+ look *FILEHANDLE, $key, $dict, $fold;
27
+
28
+ use Search::Dict;
29
+ look *FILEHANDLE, $key, $params;
30
+
31
+ =head1 DESCRIPTION
32
+
33
+ Sets file position in FILEHANDLE to be first line greater than or equal
34
+ (stringwise) to I<$key>. Returns the new file position, or -1 if an error
35
+ occurs.
36
+
37
+ The flags specify dictionary order and case folding:
38
+
39
+ If I<$dict> is true, search by dictionary order (ignore anything but word
40
+ characters and whitespace). The default is honour all characters.
41
+
42
+ If I<$fold> is true, ignore case. The default is to honour case.
43
+
44
+ If there are only three arguments and the third argument is a hash
45
+ reference, the keys of that hash can have values C<dict>, C<fold>, and
46
+ C<comp> or C<xfrm> (see below), and their corresponding values will be
47
+ used as the parameters.
48
+
49
+ If a comparison subroutine (comp) is defined, it must return less than zero,
50
+ zero, or greater than zero, if the first comparand is less than,
51
+ equal, or greater than the second comparand.
52
+
53
+ If a transformation subroutine (xfrm) is defined, its value is used to
54
+ transform the lines read from the filehandle before their comparison.
55
+
56
+ =cut
57
+
58
+ sub look {
59
+ my($fh,$key,$dict,$fold) = @_;
60
+ my ($comp, $xfrm);
61
+ if (@_ == 3 && ref $dict eq 'HASH') {
62
+ my $params = $dict;
63
+ $dict = 0;
64
+ $dict = $params->{dict} if exists $params->{dict};
65
+ $fold = $params->{fold} if exists $params->{fold};
66
+ $comp = $params->{comp} if exists $params->{comp};
67
+ $xfrm = $params->{xfrm} if exists $params->{xfrm};
68
+ }
69
+ $comp = sub { $_[0] cmp $_[1] } unless defined $comp;
70
+ local($_);
71
+ my $fno = fileno $fh;
72
+ my @stat;
73
+ if ( defined $fno && $fno >= 0 && ! tied *{$fh} ) { # real, open file
74
+ @stat = eval { stat($fh) }; # in case fileno lies
75
+ }
76
+ my($size, $blksize) = @stat[7,11];
77
+ $size = do { seek($fh,0,2); my $s = tell($fh); seek($fh,0,0); $s }
78
+ unless defined $size;
79
+ $blksize ||= 8192;
80
+ $key =~ s/[^\w\s]//g if $dict;
81
+ if ( $fold ) {
82
+ $key = fc($key);
83
+ }
84
+ # find the right block
85
+ my($min, $max) = (0, int($size / $blksize));
86
+ my $mid;
87
+ while ($max - $min > 1) {
88
+ $mid = int(($max + $min) / 2);
89
+ seek($fh, $mid * $blksize, 0)
90
+ or return -1;
91
+ <$fh> if $mid; # probably a partial line
92
+ $_ = <$fh>;
93
+ $_ = $xfrm->($_) if defined $xfrm;
94
+ chomp;
95
+ s/[^\w\s]//g if $dict;
96
+ if ( $fold ) {
97
+ $_ = fc($_);
98
+ }
99
+ if (defined($_) && $comp->($_, $key) < 0) {
100
+ $min = $mid;
101
+ }
102
+ else {
103
+ $max = $mid;
104
+ }
105
+ }
106
+ # find the right line
107
+ $min *= $blksize;
108
+ seek($fh,$min,0)
109
+ or return -1;
110
+ <$fh> if $min;
111
+ for (;;) {
112
+ $min = tell($fh);
113
+ defined($_ = <$fh>)
114
+ or last;
115
+ $_ = $xfrm->($_) if defined $xfrm;
116
+ chomp;
117
+ s/[^\w\s]//g if $dict;
118
+ if ( $fold ) {
119
+ $_ = fc($_);
120
+ }
121
+ last if $comp->($_, $key) >= 0;
122
+ }
123
+ seek($fh,$min,0);
124
+ $min;
125
+ }
126
+
127
+ 1;
git/usr/share/perl5/core_perl/Term/ANSIColor.pm ADDED
@@ -0,0 +1,1414 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Color screen output using ANSI escape sequences.
2
+ #
3
+ # This module provides utility functions (in two different forms) for coloring
4
+ # output with ANSI escape sequences.
5
+ #
6
+ # This module is sometimes used in low-memory environments, so avoid use of
7
+ # \d, \w, [:upper:], and similar constructs in the most important functions
8
+ # (color, colored, AUTOLOAD, and the generated constant functions) since
9
+ # loading the Unicode attribute files consumes a lot of memory.
10
+ #
11
+ # Ah, September, when the sysadmins turn colors and fall off the trees....
12
+ # -- Dave Van Domelen
13
+ #
14
+ # SPDX-License-Identifier: GPL-1.0-or-later OR Artistic-1.0-Perl
15
+
16
+ ##############################################################################
17
+ # Modules and declarations
18
+ ##############################################################################
19
+
20
+ package Term::ANSIColor;
21
+
22
+ use 5.008;
23
+ use strict;
24
+ use warnings;
25
+
26
+ # Also uses Carp but loads it on demand to reduce memory usage.
27
+
28
+ use Exporter;
29
+
30
+ # use Exporter plus @ISA instead of use base to reduce memory usage.
31
+ ## no critic (ClassHierarchies::ProhibitExplicitISA)
32
+
33
+ # Declare variables that should be set in BEGIN for robustness.
34
+ ## no critic (Modules::ProhibitAutomaticExportation)
35
+ our (@EXPORT, @EXPORT_OK, %EXPORT_TAGS, @ISA, $VERSION);
36
+
37
+ # We use autoloading, which sets this variable to the name of the called sub.
38
+ our $AUTOLOAD;
39
+
40
+ # Set $VERSION and everything export-related in a BEGIN block for robustness
41
+ # against circular module loading (not that we load any modules, but
42
+ # consistency is good).
43
+ BEGIN {
44
+ $VERSION = '5.01';
45
+
46
+ # All of the basic supported constants, used in %EXPORT_TAGS.
47
+ my @colorlist = qw(
48
+ CLEAR RESET BOLD DARK
49
+ FAINT ITALIC UNDERLINE UNDERSCORE
50
+ BLINK REVERSE CONCEALED
51
+
52
+ BLACK RED GREEN YELLOW
53
+ BLUE MAGENTA CYAN WHITE
54
+ ON_BLACK ON_RED ON_GREEN ON_YELLOW
55
+ ON_BLUE ON_MAGENTA ON_CYAN ON_WHITE
56
+
57
+ BRIGHT_BLACK BRIGHT_RED BRIGHT_GREEN BRIGHT_YELLOW
58
+ BRIGHT_BLUE BRIGHT_MAGENTA BRIGHT_CYAN BRIGHT_WHITE
59
+ ON_BRIGHT_BLACK ON_BRIGHT_RED ON_BRIGHT_GREEN ON_BRIGHT_YELLOW
60
+ ON_BRIGHT_BLUE ON_BRIGHT_MAGENTA ON_BRIGHT_CYAN ON_BRIGHT_WHITE
61
+ );
62
+
63
+ # 256-color constants, used in %EXPORT_TAGS.
64
+ my @colorlist256 = (
65
+ (map { ("ANSI$_", "ON_ANSI$_") } 0 .. 255),
66
+ (map { ("GREY$_", "ON_GREY$_") } 0 .. 23),
67
+ );
68
+ for my $r (0 .. 5) {
69
+ for my $g (0 .. 5) {
70
+ push(@colorlist256, map { ("RGB$r$g$_", "ON_RGB$r$g$_") } 0 .. 5);
71
+ }
72
+ }
73
+
74
+ # Exported symbol configuration.
75
+ @ISA = qw(Exporter);
76
+ @EXPORT = qw(color colored);
77
+ @EXPORT_OK = qw(uncolor colorstrip colorvalid coloralias);
78
+ %EXPORT_TAGS = (
79
+ constants => \@colorlist,
80
+ constants256 => \@colorlist256,
81
+ pushpop => [@colorlist, qw(PUSHCOLOR POPCOLOR LOCALCOLOR)],
82
+ );
83
+ Exporter::export_ok_tags('pushpop', 'constants256');
84
+ }
85
+
86
+ ##############################################################################
87
+ # Package variables
88
+ ##############################################################################
89
+
90
+ # If this is set, any color changes will implicitly push the current color
91
+ # onto the stack and then pop it at the end of the constant sequence, just as
92
+ # if LOCALCOLOR were used.
93
+ our $AUTOLOCAL;
94
+
95
+ # Caller sets this to force a reset at the end of each constant sequence.
96
+ our $AUTORESET;
97
+
98
+ # Caller sets this to force colors to be reset at the end of each line.
99
+ our $EACHLINE;
100
+
101
+ ##############################################################################
102
+ # Internal data structures
103
+ ##############################################################################
104
+
105
+ # This module does quite a bit of initialization at the time it is first
106
+ # loaded, primarily to set up the package-global %ATTRIBUTES hash. The
107
+ # entries for 256-color names are easier to handle programmatically, and
108
+ # custom colors are also imported from the environment if any are set.
109
+
110
+ # All basic supported attributes, including aliases.
111
+ #<<<
112
+ our %ATTRIBUTES = (
113
+ 'clear' => 0,
114
+ 'reset' => 0,
115
+ 'bold' => 1,
116
+ 'dark' => 2,
117
+ 'faint' => 2,
118
+ 'italic' => 3,
119
+ 'underline' => 4,
120
+ 'underscore' => 4,
121
+ 'blink' => 5,
122
+ 'reverse' => 7,
123
+ 'concealed' => 8,
124
+
125
+ 'black' => 30, 'on_black' => 40,
126
+ 'red' => 31, 'on_red' => 41,
127
+ 'green' => 32, 'on_green' => 42,
128
+ 'yellow' => 33, 'on_yellow' => 43,
129
+ 'blue' => 34, 'on_blue' => 44,
130
+ 'magenta' => 35, 'on_magenta' => 45,
131
+ 'cyan' => 36, 'on_cyan' => 46,
132
+ 'white' => 37, 'on_white' => 47,
133
+
134
+ 'bright_black' => 90, 'on_bright_black' => 100,
135
+ 'bright_red' => 91, 'on_bright_red' => 101,
136
+ 'bright_green' => 92, 'on_bright_green' => 102,
137
+ 'bright_yellow' => 93, 'on_bright_yellow' => 103,
138
+ 'bright_blue' => 94, 'on_bright_blue' => 104,
139
+ 'bright_magenta' => 95, 'on_bright_magenta' => 105,
140
+ 'bright_cyan' => 96, 'on_bright_cyan' => 106,
141
+ 'bright_white' => 97, 'on_bright_white' => 107,
142
+ );
143
+ #>>>
144
+
145
+ # Generating the 256-color codes involves a lot of codes and offsets that are
146
+ # not helped by turning them into constants.
147
+
148
+ # The first 16 256-color codes are duplicates of the 16 ANSI colors. The rest
149
+ # are RBG and greyscale values.
150
+ for my $code (0 .. 15) {
151
+ $ATTRIBUTES{"ansi$code"} = "38;5;$code";
152
+ $ATTRIBUTES{"on_ansi$code"} = "48;5;$code";
153
+ }
154
+
155
+ # 256-color RGB colors. Red, green, and blue can each be values 0 through 5,
156
+ # and the resulting 216 colors start with color 16.
157
+ for my $r (0 .. 5) {
158
+ for my $g (0 .. 5) {
159
+ for my $b (0 .. 5) {
160
+ my $code = 16 + (6 * 6 * $r) + (6 * $g) + $b;
161
+ $ATTRIBUTES{"rgb$r$g$b"} = "38;5;$code";
162
+ $ATTRIBUTES{"on_rgb$r$g$b"} = "48;5;$code";
163
+ }
164
+ }
165
+ }
166
+
167
+ # The last 256-color codes are 24 shades of grey.
168
+ for my $n (0 .. 23) {
169
+ my $code = $n + 232;
170
+ $ATTRIBUTES{"grey$n"} = "38;5;$code";
171
+ $ATTRIBUTES{"on_grey$n"} = "48;5;$code";
172
+ }
173
+
174
+ # Reverse lookup. Alphabetically first name for a sequence is preferred.
175
+ our %ATTRIBUTES_R;
176
+ for my $attr (reverse(sort(keys(%ATTRIBUTES)))) {
177
+ $ATTRIBUTES_R{ $ATTRIBUTES{$attr} } = $attr;
178
+ }
179
+
180
+ # Provide ansiN names for all 256 characters to provide a convenient flat
181
+ # namespace if one doesn't want to mess with the RGB and greyscale naming. Do
182
+ # this after creating %ATTRIBUTES_R since we want to use the canonical names
183
+ # when reversing a color.
184
+ for my $code (16 .. 255) {
185
+ $ATTRIBUTES{"ansi$code"} = "38;5;$code";
186
+ $ATTRIBUTES{"on_ansi$code"} = "48;5;$code";
187
+ }
188
+
189
+ # Import any custom colors set in the environment.
190
+ our %ALIASES;
191
+ if (exists($ENV{ANSI_COLORS_ALIASES})) {
192
+ my $spec = $ENV{ANSI_COLORS_ALIASES};
193
+ $spec =~ s{ \A \s+ }{}xms;
194
+ $spec =~ s{ \s+ \z }{}xms;
195
+
196
+ # Error reporting here is an interesting question. Use warn rather than
197
+ # carp because carp would report the line of the use or require, which
198
+ # doesn't help anyone understand what's going on, whereas seeing this code
199
+ # will be more helpful.
200
+ ## no critic (ErrorHandling::RequireCarping)
201
+ for my $definition (split(m{\s*,\s*}xms, $spec)) {
202
+ my ($new, $old) = split(m{\s*=\s*}xms, $definition, 2);
203
+ if (!$new || !$old) {
204
+ warn qq{Bad color mapping "$definition"};
205
+ } else {
206
+ my $result = eval { coloralias($new, $old) };
207
+ if (!$result) {
208
+ my $error = $@;
209
+ $error =~ s{ [ ] at [ ] .* }{}xms;
210
+ warn qq{$error in "$definition"};
211
+ }
212
+ }
213
+ }
214
+ }
215
+
216
+ # Stores the current color stack maintained by PUSHCOLOR and POPCOLOR. This
217
+ # is global and therefore not threadsafe.
218
+ our @COLORSTACK;
219
+
220
+ ##############################################################################
221
+ # Helper functions
222
+ ##############################################################################
223
+
224
+ # Stub to load the Carp module on demand.
225
+ sub croak {
226
+ my (@args) = @_;
227
+ require Carp;
228
+ Carp::croak(@args);
229
+ }
230
+
231
+ ##############################################################################
232
+ # Implementation (constant form)
233
+ ##############################################################################
234
+
235
+ # Time to have fun! We now want to define the constant subs, which are named
236
+ # the same as the attributes above but in all caps. Each constant sub needs
237
+ # to act differently depending on whether $AUTORESET is set. Without
238
+ # autoreset:
239
+ #
240
+ # BLUE "text\n" ==> "\e[34mtext\n"
241
+ #
242
+ # If $AUTORESET is set, we should instead get:
243
+ #
244
+ # BLUE "text\n" ==> "\e[34mtext\n\e[0m"
245
+ #
246
+ # The sub also needs to handle the case where it has no arguments correctly.
247
+ # Maintaining all of this as separate subs would be a major nightmare, as well
248
+ # as duplicate the %ATTRIBUTES hash, so instead we define an AUTOLOAD sub to
249
+ # define the constant subs on demand. To do that, we check the name of the
250
+ # called sub against the list of attributes, and if it's an all-caps version
251
+ # of one of them, we define the sub on the fly and then run it.
252
+ #
253
+ # If the environment variable ANSI_COLORS_DISABLED is set to a true value, or
254
+ # if the variable NO_COLOR is set, just return the arguments without adding
255
+ # any escape sequences. This is to make it easier to write scripts that also
256
+ # work on systems without any ANSI support, like Windows consoles.
257
+ #
258
+ # Avoid using character classes like [:upper:] and \w here, since they load
259
+ # Unicode character tables and consume a ton of memory. All of our constants
260
+ # only use ASCII characters.
261
+ #
262
+ ## no critic (ClassHierarchies::ProhibitAutoloading)
263
+ ## no critic (Subroutines::RequireArgUnpacking)
264
+ ## no critic (RegularExpressions::ProhibitEnumeratedClasses)
265
+ sub AUTOLOAD {
266
+ my ($sub, $attr) = $AUTOLOAD =~ m{
267
+ \A ( [a-zA-Z0-9:]* :: ([A-Z0-9_]+) ) \z
268
+ }xms;
269
+
270
+ # Check if we were called with something that doesn't look like an
271
+ # attribute.
272
+ if (!($attr && defined($ATTRIBUTES{ lc $attr }))) {
273
+ croak("undefined subroutine &$AUTOLOAD called");
274
+ }
275
+
276
+ # If colors are disabled, just return the input. Do this without
277
+ # installing a sub for (marginal, unbenchmarked) speed.
278
+ if ($ENV{ANSI_COLORS_DISABLED} || defined($ENV{NO_COLOR})) {
279
+ return join(q{}, @_);
280
+ }
281
+
282
+ # We've untainted the name of the sub.
283
+ $AUTOLOAD = $sub;
284
+
285
+ # Figure out the ANSI string to set the desired attribute.
286
+ my $escape = "\e[" . $ATTRIBUTES{ lc $attr } . 'm';
287
+
288
+ # Save the current value of $@. We can't just use local since we want to
289
+ # restore it before dispatching to the newly-created sub. (The caller may
290
+ # be colorizing output that includes $@.)
291
+ my $eval_err = $@;
292
+
293
+ # Generate the constant sub, which should still recognize some of our
294
+ # package variables. Use string eval to avoid a dependency on
295
+ # Sub::Install, even though it makes it somewhat less readable.
296
+ ## no critic (BuiltinFunctions::ProhibitStringyEval)
297
+ ## no critic (ValuesAndExpressions::ProhibitImplicitNewlines)
298
+ my $eval_result = eval qq{
299
+ sub $AUTOLOAD {
300
+ if (\$ENV{ANSI_COLORS_DISABLED} || defined(\$ENV{NO_COLOR})) {
301
+ return join(q{}, \@_);
302
+ } elsif (\$AUTOLOCAL && \@_) {
303
+ return PUSHCOLOR('$escape') . join(q{}, \@_) . POPCOLOR;
304
+ } elsif (\$AUTORESET && \@_) {
305
+ return '$escape' . join(q{}, \@_) . "\e[0m";
306
+ } else {
307
+ return '$escape' . join(q{}, \@_);
308
+ }
309
+ }
310
+ 1;
311
+ };
312
+
313
+ # Failure is an internal error, not a problem with the caller.
314
+ ## no critic (ErrorHandling::RequireCarping)
315
+ if (!$eval_result) {
316
+ die "failed to generate constant $attr: $@";
317
+ }
318
+
319
+ # Restore $@.
320
+ ## no critic (Variables::RequireLocalizedPunctuationVars)
321
+ $@ = $eval_err;
322
+
323
+ # Dispatch to the newly-created sub.
324
+ goto &$AUTOLOAD;
325
+ }
326
+ ## use critic
327
+
328
+ # Append a new color to the top of the color stack and return the top of
329
+ # the stack.
330
+ #
331
+ # $text - Any text we're applying colors to, with color escapes prepended
332
+ #
333
+ # Returns: The text passed in
334
+ sub PUSHCOLOR {
335
+ my (@text) = @_;
336
+ my $text = join(q{}, @text);
337
+
338
+ # Extract any number of color-setting escape sequences from the start of
339
+ # the string.
340
+ my ($color) = $text =~ m{ \A ( (?:\e\[ [\d;]+ m)+ ) }xms;
341
+
342
+ # If we already have a stack, append these escapes to the set from the top
343
+ # of the stack. This way, each position in the stack stores the complete
344
+ # enabled colors for that stage, at the cost of some potential
345
+ # inefficiency.
346
+ if (@COLORSTACK) {
347
+ $color = $COLORSTACK[-1] . $color;
348
+ }
349
+
350
+ # Push the color onto the stack.
351
+ push(@COLORSTACK, $color);
352
+ return $text;
353
+ }
354
+
355
+ # Pop the color stack and return the new top of the stack (or reset, if
356
+ # the stack is empty).
357
+ #
358
+ # @text - Any text we're applying colors to
359
+ #
360
+ # Returns: The concatenation of @text prepended with the new stack color
361
+ sub POPCOLOR {
362
+ my (@text) = @_;
363
+ pop(@COLORSTACK);
364
+ if (@COLORSTACK) {
365
+ return $COLORSTACK[-1] . join(q{}, @text);
366
+ } else {
367
+ return RESET(@text);
368
+ }
369
+ }
370
+
371
+ # Surround arguments with a push and a pop. The effect will be to reset the
372
+ # colors to whatever was on the color stack before this sequence of colors was
373
+ # applied.
374
+ #
375
+ # @text - Any text we're applying colors to
376
+ #
377
+ # Returns: The concatenation of the text and the proper color reset sequence.
378
+ sub LOCALCOLOR {
379
+ my (@text) = @_;
380
+ return PUSHCOLOR(join(q{}, @text)) . POPCOLOR();
381
+ }
382
+
383
+ ##############################################################################
384
+ # Implementation (attribute string form)
385
+ ##############################################################################
386
+
387
+ # Return the escape code for a given set of color attributes.
388
+ #
389
+ # @codes - A list of possibly space-separated color attributes
390
+ #
391
+ # Returns: The escape sequence setting those color attributes
392
+ # undef if no escape sequences were given
393
+ # Throws: Text exception for any invalid attribute
394
+ sub color {
395
+ my (@codes) = @_;
396
+
397
+ # Return the empty string if colors are disabled.
398
+ if ($ENV{ANSI_COLORS_DISABLED} || defined($ENV{NO_COLOR})) {
399
+ return q{};
400
+ }
401
+
402
+ # Split on whitespace and expand aliases.
403
+ @codes = map { split } @codes;
404
+ @codes = map { defined($ALIASES{$_}) ? @{ $ALIASES{$_} } : $_ } @codes;
405
+
406
+ # Build the attribute string from semicolon-separated numbers.
407
+ ## no critic (RegularExpressions::ProhibitEnumeratedClasses)
408
+ my $attribute = q{};
409
+ for my $code (@codes) {
410
+ $code = lc($code);
411
+ if (defined($ATTRIBUTES{$code})) {
412
+ $attribute .= $ATTRIBUTES{$code} . q{;};
413
+ } elsif ($code =~ m{ \A (on_)? r([0-9]+) g([0-9]+) b([0-9]+) \z }xms) {
414
+ my ($r, $g, $b) = ($2 + 0, $3 + 0, $4 + 0);
415
+ if ($r > 255 || $g > 255 || $b > 255) {
416
+ croak("Invalid attribute name $code");
417
+ }
418
+ my $prefix = $1 ? '48' : '38';
419
+ $attribute .= "$prefix;2;$r;$g;$b;";
420
+ } else {
421
+ croak("Invalid attribute name $code");
422
+ }
423
+ }
424
+ ## use critic
425
+
426
+ # We added one too many semicolons for simplicity. Remove the last one.
427
+ chop($attribute);
428
+
429
+ # Return undef if there were no attributes.
430
+ return ($attribute ne q{}) ? "\e[${attribute}m" : undef;
431
+ }
432
+
433
+ # Return a list of named color attributes for a given set of escape codes.
434
+ # Escape sequences can be given with or without enclosing "\e[" and "m". The
435
+ # empty escape sequence '' or "\e[m" gives an empty list of attrs.
436
+ #
437
+ # There is one special case. 256-color codes start with 38 or 48, followed by
438
+ # a 5 and then the 256-color code.
439
+ #
440
+ # @escapes - A list of escape sequences or escape sequence numbers
441
+ #
442
+ # Returns: An array of attribute names corresponding to those sequences
443
+ # Throws: Text exceptions on invalid escape sequences or unknown colors
444
+ sub uncolor {
445
+ my (@escapes) = @_;
446
+ my (@nums, @result);
447
+
448
+ # Walk the list of escapes and build a list of attribute numbers.
449
+ for my $escape (@escapes) {
450
+ $escape =~ s{ \A \e\[ }{}xms;
451
+ $escape =~ s{ m \z } {}xms;
452
+ my ($attrs) = $escape =~ m{ \A ((?:\d+;)* \d*) \z }xms;
453
+ if (!defined($attrs)) {
454
+ croak("Bad escape sequence $escape");
455
+ }
456
+
457
+ # Pull off 256-color codes (38;5;n or 48;5;n) and true color codes
458
+ # (38;2;n;n;n or 48;2;n;n;n) as a unit.
459
+ my $regex = qr{
460
+ (
461
+ 0*[34]8 ; 0*2 ; \d+ ; \d+ ; \d+
462
+ | 0*[34]8 ; 0*5 ; \d+
463
+ | \d+
464
+ )
465
+ (?: ; | \z )
466
+ }xms;
467
+ push(@nums, $attrs =~ m{$regex}xmsg);
468
+ }
469
+
470
+ # Now, walk the list of numbers and convert them to attribute names.
471
+ # Strip leading zeroes from any of the numbers. (xterm, at least, allows
472
+ # leading zeroes to be added to any number in an escape sequence.)
473
+ for my $num (@nums) {
474
+ if ($num =~ m{ \A 0*([34])8 ; 0*2 ; (\d+) ; (\d+) ; (\d+) \z }xms) {
475
+ my ($r, $g, $b) = ($2 + 0, $3 + 0, $4 + 0);
476
+ if ($r > 255 || $g > 255 || $b > 255) {
477
+ croak("No name for escape sequence $num");
478
+ }
479
+ my $prefix = ($1 == 4) ? 'on_' : q{};
480
+ push(@result, "${prefix}r${r}g${g}b${b}");
481
+ } else {
482
+ $num =~ s{ ( \A | ; ) 0+ (\d) }{$1$2}xmsg;
483
+ my $name = $ATTRIBUTES_R{$num};
484
+ if (!defined($name)) {
485
+ croak("No name for escape sequence $num");
486
+ }
487
+ push(@result, $name);
488
+ }
489
+ }
490
+
491
+ # Return the attribute names.
492
+ return @result;
493
+ }
494
+
495
+ # Given a string and a set of attributes, returns the string surrounded by
496
+ # escape codes to set those attributes and then clear them at the end of the
497
+ # string. The attributes can be given either as an array ref as the first
498
+ # argument or as a list as the second and subsequent arguments.
499
+ #
500
+ # If $EACHLINE is set, insert a reset before each occurrence of the string
501
+ # $EACHLINE and the starting attribute code after the string $EACHLINE, so
502
+ # that no attribute crosses line delimiters (this is often desirable if the
503
+ # output is to be piped to a pager or some other program).
504
+ #
505
+ # $first - An anonymous array of attributes or the text to color
506
+ # @rest - The text to color or the list of attributes
507
+ #
508
+ # Returns: The text, concatenated if necessary, surrounded by escapes to set
509
+ # the desired colors and reset them afterwards
510
+ # Throws: Text exception on invalid attributes
511
+ sub colored {
512
+ my ($first, @rest) = @_;
513
+ my ($string, @codes);
514
+ if (ref($first) && ref($first) eq 'ARRAY') {
515
+ @codes = @{$first};
516
+ $string = join(q{}, @rest);
517
+ } else {
518
+ $string = $first;
519
+ @codes = @rest;
520
+ }
521
+
522
+ # Return the string unmolested if colors are disabled.
523
+ if ($ENV{ANSI_COLORS_DISABLED} || defined($ENV{NO_COLOR})) {
524
+ return $string;
525
+ }
526
+
527
+ # Find the attribute string for our colors.
528
+ my $attr = color(@codes);
529
+
530
+ # If $EACHLINE is defined, split the string on line boundaries, suppress
531
+ # empty segments, and then colorize each of the line sections.
532
+ if (defined($EACHLINE)) {
533
+ my @text = map { ($_ ne $EACHLINE) ? $attr . $_ . "\e[0m" : $_ }
534
+ grep { length > 0 }
535
+ split(m{ (\Q$EACHLINE\E) }xms, $string);
536
+ return join(q{}, @text);
537
+ } else {
538
+ return $attr . $string . "\e[0m";
539
+ }
540
+ }
541
+
542
+ # Define a new color alias, or return the value of an existing alias.
543
+ #
544
+ # $alias - The color alias to define
545
+ # @color - The color attributes the alias will correspond to (optional)
546
+ #
547
+ # Returns: The standard color value of the alias as a string (may be multiple
548
+ # attributes separated by spaces)
549
+ # undef if one argument was given and the alias was not recognized
550
+ # Throws: Text exceptions for invalid alias names, attempts to use a
551
+ # standard color name as an alias, or an unknown standard color name
552
+ sub coloralias {
553
+ my ($alias, @color) = @_;
554
+ if (!@color) {
555
+ if (exists($ALIASES{$alias})) {
556
+ return join(q{ }, @{ $ALIASES{$alias} });
557
+ } else {
558
+ return;
559
+ }
560
+ }
561
+
562
+ # Avoid \w here to not load Unicode character tables, which increases the
563
+ # memory footprint of this module considerably.
564
+ #
565
+ ## no critic (RegularExpressions::ProhibitEnumeratedClasses)
566
+ if ($alias !~ m{ \A [a-zA-Z0-9._-]+ \z }xms) {
567
+ croak(qq{Invalid alias name "$alias"});
568
+ } elsif ($ATTRIBUTES{$alias}) {
569
+ croak(qq{Cannot alias standard color "$alias"});
570
+ }
571
+ ## use critic
572
+
573
+ # Split on whitespace and expand aliases.
574
+ @color = map { split } @color;
575
+ @color = map { defined($ALIASES{$_}) ? @{ $ALIASES{$_} } : $_ } @color;
576
+
577
+ # Check that all of the attributes are valid.
578
+ for my $attribute (@color) {
579
+ if (!exists($ATTRIBUTES{$attribute})) {
580
+ croak(qq{Invalid attribute name "$attribute"});
581
+ }
582
+ }
583
+
584
+ # Set the alias and return.
585
+ $ALIASES{$alias} = [@color];
586
+ return join(q{ }, @color);
587
+ }
588
+
589
+ # Given a string, strip the ANSI color codes out of that string and return the
590
+ # result. This removes only ANSI color codes, not movement codes and other
591
+ # escape sequences.
592
+ #
593
+ # @string - The list of strings to sanitize
594
+ #
595
+ # Returns: (array) The strings stripped of ANSI color escape sequences
596
+ # (scalar) The same, concatenated
597
+ sub colorstrip {
598
+ my (@string) = @_;
599
+ for my $string (@string) {
600
+ $string =~ s{ \e\[ [\d;]* m }{}xmsg;
601
+ }
602
+ return wantarray ? @string : join(q{}, @string);
603
+ }
604
+
605
+ # Given a list of color attributes (arguments for color, for instance), return
606
+ # true if they're all valid or false if any of them are invalid.
607
+ #
608
+ # @codes - A list of color attributes, possibly space-separated
609
+ #
610
+ # Returns: True if all the attributes are valid, false otherwise.
611
+ sub colorvalid {
612
+ my (@codes) = @_;
613
+ @codes = map { split(q{ }, lc) } @codes;
614
+ for my $code (@codes) {
615
+ next if defined($ATTRIBUTES{$code});
616
+ next if defined($ALIASES{$code});
617
+ if ($code =~ m{ \A (?: on_ )? r (\d+) g (\d+) b (\d+) \z }xms) {
618
+ next if ($1 <= 255 && $2 <= 255 && $3 <= 255);
619
+ }
620
+ return;
621
+ }
622
+ return 1;
623
+ }
624
+
625
+ ##############################################################################
626
+ # Module return value and documentation
627
+ ##############################################################################
628
+
629
+ # Ensure we evaluate to true.
630
+ 1;
631
+ __END__
632
+
633
+ =head1 NAME
634
+
635
+ Term::ANSIColor - Color screen output using ANSI escape sequences
636
+
637
+ =for stopwords
638
+ cyan colorize namespace runtime TMTOWTDI cmd.exe cmd.exe. 4nt.exe. 4nt.exe
639
+ command.com NT ESC Delvare SSH OpenSSH aixterm ECMA-048 Fraktur overlining
640
+ Zenin reimplemented Allbery PUSHCOLOR POPCOLOR LOCALCOLOR openmethods.com
641
+ openmethods.com. grey ATTR urxvt mistyped prepending Bareword filehandle
642
+ Cygwin Starsinic aterm rxvt CPAN RGB Solarized Whitespace alphanumerics
643
+ undef CLICOLOR NNN GGG RRR
644
+
645
+ =head1 SYNOPSIS
646
+
647
+ use Term::ANSIColor;
648
+ print color('bold blue');
649
+ print "This text is bold blue.\n";
650
+ print color('reset');
651
+ print "This text is normal.\n";
652
+ print colored("Yellow on magenta.", 'yellow on_magenta'), "\n";
653
+ print "This text is normal.\n";
654
+ print colored(['yellow on_magenta'], 'Yellow on magenta.', "\n");
655
+ print colored(['red on_bright_yellow'], 'Red on bright yellow.', "\n");
656
+ print colored(['bright_red on_black'], 'Bright red on black.', "\n");
657
+ print "\n";
658
+
659
+ # Map escape sequences back to color names.
660
+ use Term::ANSIColor 1.04 qw(uncolor);
661
+ my @names = uncolor('01;31');
662
+ print join(q{ }, @names), "\n";
663
+
664
+ # Strip all color escape sequences.
665
+ use Term::ANSIColor 2.01 qw(colorstrip);
666
+ print colorstrip("\e[1mThis is bold\e[0m"), "\n";
667
+
668
+ # Determine whether a color is valid.
669
+ use Term::ANSIColor 2.02 qw(colorvalid);
670
+ my $valid = colorvalid('blue bold', 'on_magenta');
671
+ print "Color string is ", $valid ? "valid\n" : "invalid\n";
672
+
673
+ # Create new aliases for colors.
674
+ use Term::ANSIColor 4.00 qw(coloralias);
675
+ coloralias('alert', 'red');
676
+ print "Alert is ", coloralias('alert'), "\n";
677
+ print colored("This is in red.", 'alert'), "\n";
678
+
679
+ use Term::ANSIColor qw(:constants);
680
+ print BOLD, BLUE, "This text is in bold blue.\n", RESET;
681
+
682
+ use Term::ANSIColor qw(:constants);
683
+ {
684
+ local $Term::ANSIColor::AUTORESET = 1;
685
+ print BOLD BLUE "This text is in bold blue.\n";
686
+ print "This text is normal.\n";
687
+ }
688
+
689
+ use Term::ANSIColor 2.00 qw(:pushpop);
690
+ print PUSHCOLOR RED ON_GREEN "This text is red on green.\n";
691
+ print PUSHCOLOR BRIGHT_BLUE "This text is bright blue on green.\n";
692
+ print RESET BRIGHT_BLUE "This text is just bright blue.\n";
693
+ print POPCOLOR "Back to red on green.\n";
694
+ print LOCALCOLOR GREEN ON_BLUE "This text is green on blue.\n";
695
+ print "This text is red on green.\n";
696
+ {
697
+ local $Term::ANSIColor::AUTOLOCAL = 1;
698
+ print ON_BLUE "This text is red on blue.\n";
699
+ print "This text is red on green.\n";
700
+ }
701
+ print POPCOLOR "Back to whatever we started as.\n";
702
+
703
+ =head1 DESCRIPTION
704
+
705
+ This module has two interfaces, one through color() and colored() and the
706
+ other through constants. It also offers the utility functions uncolor(),
707
+ colorstrip(), colorvalid(), and coloralias(), which have to be explicitly
708
+ imported to be used (see L</SYNOPSIS>).
709
+
710
+ If you are using Term::ANSIColor in a console command, consider supporting the
711
+ CLICOLOR standard. See L</"Supporting CLICOLOR"> for more information.
712
+
713
+ See L</COMPATIBILITY> for the versions of Term::ANSIColor that introduced
714
+ particular features and the versions of Perl that included them.
715
+
716
+ =head2 Supported Colors
717
+
718
+ Terminal emulators that support color divide into four types: ones that
719
+ support only eight colors, ones that support sixteen, ones that support 256,
720
+ and ones that support 24-bit color. This module provides the ANSI escape
721
+ codes for all of them. These colors are referred to as ANSI colors 0 through
722
+ 7 (normal), 8 through 15 (16-color), 16 through 255 (256-color), and true
723
+ color (called direct-color by B<xterm>).
724
+
725
+ Unfortunately, interpretation of colors 0 through 7 often depends on
726
+ whether the emulator supports eight colors or sixteen colors. Emulators
727
+ that only support eight colors (such as the Linux console) will display
728
+ colors 0 through 7 with normal brightness and ignore colors 8 through 15,
729
+ treating them the same as white. Emulators that support 16 colors, such
730
+ as gnome-terminal, normally display colors 0 through 7 as dim or darker
731
+ versions and colors 8 through 15 as normal brightness. On such emulators,
732
+ the "normal" white (color 7) usually is shown as pale grey, requiring
733
+ bright white (15) to be used to get a real white color. Bright black
734
+ usually is a dark grey color, although some terminals display it as pure
735
+ black. Some sixteen-color terminal emulators also treat normal yellow
736
+ (color 3) as orange or brown, and bright yellow (color 11) as yellow.
737
+
738
+ Following the normal convention of sixteen-color emulators, this module
739
+ provides a pair of attributes for each color. For every normal color (0
740
+ through 7), the corresponding bright color (8 through 15) is obtained by
741
+ prepending the string C<bright_> to the normal color name. For example,
742
+ C<red> is color 1 and C<bright_red> is color 9. The same applies for
743
+ background colors: C<on_red> is the normal color and C<on_bright_red> is
744
+ the bright color. Capitalize these strings for the constant interface.
745
+
746
+ There is unfortunately no way to know whether the current emulator
747
+ supports more than eight colors, which makes the choice of colors
748
+ difficult. The most conservative choice is to use only the regular
749
+ colors, which are at least displayed on all emulators. However, they will
750
+ appear dark in sixteen-color terminal emulators, including most common
751
+ emulators in UNIX X environments. If you know the display is one of those
752
+ emulators, you may wish to use the bright variants instead. Even better,
753
+ offer the user a way to configure the colors for a given application to
754
+ fit their terminal emulator.
755
+
756
+ For 256-color emulators, this module additionally provides C<ansi0>
757
+ through C<ansi15>, which are the same as colors 0 through 15 in
758
+ sixteen-color emulators but use the 256-color escape syntax, C<grey0>
759
+ through C<grey23> ranging from nearly black to nearly white, and a set of
760
+ RGB colors. The RGB colors are of the form C<rgbI<RGB>> where I<R>, I<G>,
761
+ and I<B> are numbers from 0 to 5 giving the intensity of red, green, and
762
+ blue. The grey and RGB colors are also available as C<ansi16> through
763
+ C<ansi255> if you want simple names for all 256 colors. C<on_> variants
764
+ of all of these colors are also provided. These colors may be ignored
765
+ completely on non-256-color terminals or may be misinterpreted and produce
766
+ random behavior. Additional attributes such as blink, italic, or bold may
767
+ not work with the 256-color palette.
768
+
769
+ For true color emulators, this module supports attributes of the form C<<
770
+ rI<NNN>gI<NNN>bI<NNN> >> and C<< on_rI<NNN>gI<NNN>bI<NNN> >> for all values of
771
+ I<NNN> between 0 and 255. These represent foreground and background colors,
772
+ respectively, with the RGB values given by the I<NNN> numbers. These colors
773
+ may be ignored completely on non-true-color terminals or may be misinterpreted
774
+ and produce random behavior.
775
+
776
+ =head2 Function Interface
777
+
778
+ The function interface uses attribute strings to describe the colors and
779
+ text attributes to assign to text. The recognized non-color attributes
780
+ are clear, reset, bold, dark, faint, italic, underline, underscore, blink,
781
+ reverse, and concealed. Clear and reset (reset to default attributes),
782
+ dark and faint (dim and saturated), and underline and underscore are
783
+ equivalent, so use whichever is the most intuitive to you.
784
+
785
+ Note that not all attributes are supported by all terminal types, and some
786
+ terminals may not support any of these sequences. Dark and faint, italic,
787
+ blink, and concealed in particular are frequently not implemented.
788
+
789
+ The recognized normal foreground color attributes (colors 0 to 7) are:
790
+
791
+ black red green yellow blue magenta cyan white
792
+
793
+ The corresponding bright foreground color attributes (colors 8 to 15) are:
794
+
795
+ bright_black bright_red bright_green bright_yellow
796
+ bright_blue bright_magenta bright_cyan bright_white
797
+
798
+ The recognized normal background color attributes (colors 0 to 7) are:
799
+
800
+ on_black on_red on_green on yellow
801
+ on_blue on_magenta on_cyan on_white
802
+
803
+ The recognized bright background color attributes (colors 8 to 15) are:
804
+
805
+ on_bright_black on_bright_red on_bright_green on_bright_yellow
806
+ on_bright_blue on_bright_magenta on_bright_cyan on_bright_white
807
+
808
+ For 256-color terminals, the recognized foreground colors are:
809
+
810
+ ansi0 .. ansi255
811
+ grey0 .. grey23
812
+
813
+ plus C<rgbI<RGB>> for I<R>, I<G>, and I<B> values from 0 to 5, such as
814
+ C<rgb000> or C<rgb515>. Similarly, the recognized background colors are:
815
+
816
+ on_ansi0 .. on_ansi255
817
+ on_grey0 .. on_grey23
818
+
819
+ plus C<on_rgbI<RGB>> for I<R>, I<G>, and I<B> values from 0 to 5.
820
+
821
+ For true color terminals, the recognized foreground colors are C<<
822
+ rI<RRR>gI<GGG>bI<BBB> >> for I<RRR>, I<GGG>, and I<BBB> values between 0 and
823
+ 255. Similarly, the recognized background colors are C<<
824
+ on_rI<RRR>gI<GGG>bI<BBB> >> for I<RRR>, I<GGG>, and I<BBB> values between 0
825
+ and 255.
826
+
827
+ For any of the above listed attributes, case is not significant.
828
+
829
+ Attributes, once set, last until they are unset (by printing the attribute
830
+ C<clear> or C<reset>). Be careful to do this, or otherwise your attribute
831
+ will last after your script is done running, and people get very annoyed
832
+ at having their prompt and typing changed to weird colors.
833
+
834
+ =over 4
835
+
836
+ =item color(ATTR[, ATTR ...])
837
+
838
+ color() takes any number of strings as arguments and considers them to be
839
+ space-separated lists of attributes. It then forms and returns the escape
840
+ sequence to set those attributes. It doesn't print it out, just returns
841
+ it, so you'll have to print it yourself if you want to. This is so that
842
+ you can save it as a string, pass it to something else, send it to a file
843
+ handle, or do anything else with it that you might care to. color()
844
+ throws an exception if given an invalid attribute.
845
+
846
+ =item colored(STRING, ATTR[, ATTR ...])
847
+
848
+ =item colored(ATTR-REF, STRING[, STRING...])
849
+
850
+ As an aid in resetting colors, colored() takes a scalar as the first
851
+ argument and any number of attribute strings as the second argument and
852
+ returns the scalar wrapped in escape codes so that the attributes will be
853
+ set as requested before the string and reset to normal after the string.
854
+ Alternately, you can pass a reference to an array as the first argument,
855
+ and then the contents of that array will be taken as attributes and color
856
+ codes and the remainder of the arguments as text to colorize.
857
+
858
+ Normally, colored() just puts attribute codes at the beginning and end of
859
+ the string, but if you set $Term::ANSIColor::EACHLINE to some string, that
860
+ string will be considered the line delimiter and the attribute will be set
861
+ at the beginning of each line of the passed string and reset at the end of
862
+ each line. This is often desirable if the output contains newlines and
863
+ you're using background colors, since a background color that persists
864
+ across a newline is often interpreted by the terminal as providing the
865
+ default background color for the next line. Programs like pagers can also
866
+ be confused by attributes that span lines. Normally you'll want to set
867
+ $Term::ANSIColor::EACHLINE to C<"\n"> to use this feature.
868
+
869
+ Particularly consider setting $Term::ANSIColor::EACHLINE if you are
870
+ interleaving output to standard output and standard error and you aren't
871
+ flushing standard output (via autoflush() or setting C<$|>). If you don't,
872
+ the code to reset the color may unexpectedly sit in the standard output buffer
873
+ rather than going to the display, causing standard error output to appear in
874
+ the wrong color.
875
+
876
+ =item uncolor(ESCAPE)
877
+
878
+ uncolor() performs the opposite translation as color(), turning escape
879
+ sequences into a list of strings corresponding to the attributes being set
880
+ by those sequences. uncolor() will never return C<ansi16> through
881
+ C<ansi255>, instead preferring the C<grey> and C<rgb> names (and likewise
882
+ for C<on_ansi16> through C<on_ansi255>).
883
+
884
+ =item colorstrip(STRING[, STRING ...])
885
+
886
+ colorstrip() removes all color escape sequences from the provided strings,
887
+ returning the modified strings separately in array context or joined
888
+ together in scalar context. Its arguments are not modified.
889
+
890
+ =item colorvalid(ATTR[, ATTR ...])
891
+
892
+ colorvalid() takes attribute strings the same as color() and returns true
893
+ if all attributes are known and false otherwise.
894
+
895
+ =item coloralias(ALIAS[, ATTR ...])
896
+
897
+ If ATTR is specified, it is interpreted as a list of space-separated strings
898
+ naming attributes or existing aliases. In this case, coloralias() sets up an
899
+ alias of ALIAS for the set of attributes given by ATTR. From that point
900
+ forward, ALIAS can be passed into color(), colored(), and colorvalid() and
901
+ will have the same meaning as the sequence of attributes given in ATTR. One
902
+ possible use of this facility is to give more meaningful names to the
903
+ 256-color RGB colors. Only ASCII alphanumerics, C<.>, C<_>, and C<-> are
904
+ allowed in alias names.
905
+
906
+ If ATTR includes aliases, those aliases will be expanded at definition time
907
+ and their values will be used to define the new alias. This means that if you
908
+ define an alias A in terms of another alias B, and then later redefine alias
909
+ B, the value of alias A will not change.
910
+
911
+ If ATTR is not specified, coloralias() returns the standard attribute or
912
+ attributes to which ALIAS is aliased, if any, or undef if ALIAS does not
913
+ exist. If it is aliased to multiple attributes, the return value will be a
914
+ single string and the attributes will be separated by spaces.
915
+
916
+ This is the same facility used by the ANSI_COLORS_ALIASES environment
917
+ variable (see L</ENVIRONMENT> below) but can be used at runtime, not just
918
+ when the module is loaded.
919
+
920
+ Later invocations of coloralias() with the same ALIAS will override
921
+ earlier aliases. There is no way to remove an alias.
922
+
923
+ Aliases have no effect on the return value of uncolor().
924
+
925
+ B<WARNING>: Aliases are global and affect all callers in the same process.
926
+ There is no way to set an alias limited to a particular block of code or a
927
+ particular object.
928
+
929
+ =back
930
+
931
+ =head2 Constant Interface
932
+
933
+ Alternately, if you import C<:constants>, you can use the following
934
+ constants directly:
935
+
936
+ CLEAR RESET BOLD DARK
937
+ FAINT ITALIC UNDERLINE UNDERSCORE
938
+ BLINK REVERSE CONCEALED
939
+
940
+ BLACK RED GREEN YELLOW
941
+ BLUE MAGENTA CYAN WHITE
942
+ BRIGHT_BLACK BRIGHT_RED BRIGHT_GREEN BRIGHT_YELLOW
943
+ BRIGHT_BLUE BRIGHT_MAGENTA BRIGHT_CYAN BRIGHT_WHITE
944
+
945
+ ON_BLACK ON_RED ON_GREEN ON_YELLOW
946
+ ON_BLUE ON_MAGENTA ON_CYAN ON_WHITE
947
+ ON_BRIGHT_BLACK ON_BRIGHT_RED ON_BRIGHT_GREEN ON_BRIGHT_YELLOW
948
+ ON_BRIGHT_BLUE ON_BRIGHT_MAGENTA ON_BRIGHT_CYAN ON_BRIGHT_WHITE
949
+
950
+ These are the same as color('attribute') and can be used if you prefer
951
+ typing:
952
+
953
+ print BOLD BLUE ON_WHITE "Text", RESET, "\n";
954
+
955
+ to
956
+
957
+ print colored ("Text", 'bold blue on_white'), "\n";
958
+
959
+ (Note that the newline is kept separate to avoid confusing the terminal as
960
+ described above since a background color is being used.)
961
+
962
+ If you import C<:constants256>, you can use the following constants
963
+ directly:
964
+
965
+ ANSI0 .. ANSI255
966
+ GREY0 .. GREY23
967
+
968
+ RGBXYZ (for X, Y, and Z values from 0 to 5, like RGB000 or RGB515)
969
+
970
+ ON_ANSI0 .. ON_ANSI255
971
+ ON_GREY0 .. ON_GREY23
972
+
973
+ ON_RGBXYZ (for X, Y, and Z values from 0 to 5)
974
+
975
+ Note that C<:constants256> does not include the other constants, so if you
976
+ want to mix both, you need to include C<:constants> as well. You may want
977
+ to explicitly import at least C<RESET>, as in:
978
+
979
+ use Term::ANSIColor 4.00 qw(RESET :constants256);
980
+
981
+ True color and aliases are not supported by the constant interface.
982
+
983
+ When using the constants, if you don't want to have to remember to add the
984
+ C<, RESET> at the end of each print line, you can set
985
+ $Term::ANSIColor::AUTORESET to a true value. Then, the display mode will
986
+ automatically be reset if there is no comma after the constant. In other
987
+ words, with that variable set:
988
+
989
+ print BOLD BLUE "Text\n";
990
+
991
+ will reset the display mode afterward, whereas:
992
+
993
+ print BOLD, BLUE, "Text\n";
994
+
995
+ will not. If you are using background colors, you will probably want to
996
+ either use say() (in newer versions of Perl) or print the newline with a
997
+ separate print statement to avoid confusing the terminal.
998
+
999
+ If $Term::ANSIColor::AUTOLOCAL is set (see below), it takes precedence
1000
+ over $Term::ANSIColor::AUTORESET, and the latter is ignored.
1001
+
1002
+ The subroutine interface has the advantage over the constants interface in
1003
+ that only two subroutines are exported into your namespace, versus
1004
+ thirty-eight in the constants interface, and aliases and true color attributes
1005
+ are supported. On the flip side, the constants interface has the advantage of
1006
+ better compile time error checking, since misspelled names of colors or
1007
+ attributes in calls to color() and colored() won't be caught until runtime
1008
+ whereas misspelled names of constants will be caught at compile time. So,
1009
+ pollute your namespace with almost two dozen subroutines that you may not even
1010
+ use that often, or risk a silly bug by mistyping an attribute. Your choice,
1011
+ TMTOWTDI after all.
1012
+
1013
+ =head2 The Color Stack
1014
+
1015
+ You can import C<:pushpop> and maintain a stack of colors using PUSHCOLOR,
1016
+ POPCOLOR, and LOCALCOLOR. PUSHCOLOR takes the attribute string that
1017
+ starts its argument and pushes it onto a stack of attributes. POPCOLOR
1018
+ removes the top of the stack and restores the previous attributes set by
1019
+ the argument of a prior PUSHCOLOR. LOCALCOLOR surrounds its argument in a
1020
+ PUSHCOLOR and POPCOLOR so that the color resets afterward.
1021
+
1022
+ If $Term::ANSIColor::AUTOLOCAL is set, each sequence of color constants
1023
+ will be implicitly preceded by LOCALCOLOR. In other words, the following:
1024
+
1025
+ {
1026
+ local $Term::ANSIColor::AUTOLOCAL = 1;
1027
+ print BLUE "Text\n";
1028
+ }
1029
+
1030
+ is equivalent to:
1031
+
1032
+ print LOCALCOLOR BLUE "Text\n";
1033
+
1034
+ If $Term::ANSIColor::AUTOLOCAL is set, it takes precedence over
1035
+ $Term::ANSIColor::AUTORESET, and the latter is ignored.
1036
+
1037
+ When using PUSHCOLOR, POPCOLOR, and LOCALCOLOR, it's particularly
1038
+ important to not put commas between the constants.
1039
+
1040
+ print PUSHCOLOR BLUE "Text\n";
1041
+
1042
+ will correctly push BLUE onto the top of the stack.
1043
+
1044
+ print PUSHCOLOR, BLUE, "Text\n"; # wrong!
1045
+
1046
+ will not, and a subsequent pop won't restore the correct attributes.
1047
+ PUSHCOLOR pushes the attributes set by its argument, which is normally a
1048
+ string of color constants. It can't ask the terminal what the current
1049
+ attributes are.
1050
+
1051
+ =head2 Supporting CLICOLOR
1052
+
1053
+ L<https://bixense.com/clicolors/> proposes a standard for enabling and
1054
+ disabling color output from console commands using two environment variables,
1055
+ CLICOLOR and CLICOLOR_FORCE. Term::ANSIColor cannot automatically support
1056
+ this standard, since the correct action depends on where the output is going
1057
+ and Term::ANSIColor may be used in a context where colors should always be
1058
+ generated even if CLICOLOR is set in the environment. But you can use the
1059
+ supported environment variable ANSI_COLORS_DISABLED to implement CLICOLOR in
1060
+ your own programs with code like this:
1061
+
1062
+ if (exists($ENV{CLICOLOR}) && $ENV{CLICOLOR} == 0) {
1063
+ if (!$ENV{CLICOLOR_FORCE}) {
1064
+ $ENV{ANSI_COLORS_DISABLED} = 1;
1065
+ }
1066
+ }
1067
+
1068
+ If you are using the constant interface, be sure to include this code before
1069
+ you use any color constants (such as at the very top of your script), since
1070
+ this environment variable is only honored the first time a color constant is
1071
+ seen.
1072
+
1073
+ Be aware that this will export ANSI_COLORS_DISABLED to any child processes of
1074
+ your program as well.
1075
+
1076
+ =head1 DIAGNOSTICS
1077
+
1078
+ =over 4
1079
+
1080
+ =item Bad color mapping %s
1081
+
1082
+ (W) The specified color mapping from ANSI_COLORS_ALIASES is not valid and
1083
+ could not be parsed. It was ignored.
1084
+
1085
+ =item Bad escape sequence %s
1086
+
1087
+ (F) You passed an invalid ANSI escape sequence to uncolor().
1088
+
1089
+ =item Bareword "%s" not allowed while "strict subs" in use
1090
+
1091
+ (F) You probably mistyped a constant color name such as:
1092
+
1093
+ $Foobar = FOOBAR . "This line should be blue\n";
1094
+
1095
+ or:
1096
+
1097
+ @Foobar = FOOBAR, "This line should be blue\n";
1098
+
1099
+ This will only show up under use strict (another good reason to run under
1100
+ use strict).
1101
+
1102
+ =item Cannot alias standard color %s
1103
+
1104
+ (F) The alias name passed to coloralias() matches a standard color name.
1105
+ Standard color names cannot be aliased.
1106
+
1107
+ =item Cannot alias standard color %s in %s
1108
+
1109
+ (W) The same, but in ANSI_COLORS_ALIASES. The color mapping was ignored.
1110
+
1111
+ =item Invalid alias name %s
1112
+
1113
+ (F) You passed an invalid alias name to coloralias(). Alias names must
1114
+ consist only of alphanumerics, C<.>, C<->, and C<_>.
1115
+
1116
+ =item Invalid alias name %s in %s
1117
+
1118
+ (W) You specified an invalid alias name on the left hand of the equal sign
1119
+ in a color mapping in ANSI_COLORS_ALIASES. The color mapping was ignored.
1120
+
1121
+ =item Invalid attribute name %s
1122
+
1123
+ (F) You passed an invalid attribute name to color(), colored(), or
1124
+ coloralias().
1125
+
1126
+ =item Invalid attribute name %s in %s
1127
+
1128
+ (W) You specified an invalid attribute name on the right hand of the equal
1129
+ sign in a color mapping in ANSI_COLORS_ALIASES. The color mapping was
1130
+ ignored.
1131
+
1132
+ =item Name "%s" used only once: possible typo
1133
+
1134
+ (W) You probably mistyped a constant color name such as:
1135
+
1136
+ print FOOBAR "This text is color FOOBAR\n";
1137
+
1138
+ It's probably better to always use commas after constant names in order to
1139
+ force the next error.
1140
+
1141
+ =item No comma allowed after filehandle
1142
+
1143
+ (F) You probably mistyped a constant color name such as:
1144
+
1145
+ print FOOBAR, "This text is color FOOBAR\n";
1146
+
1147
+ Generating this fatal compile error is one of the main advantages of using
1148
+ the constants interface, since you'll immediately know if you mistype a
1149
+ color name.
1150
+
1151
+ =item No name for escape sequence %s
1152
+
1153
+ (F) The ANSI escape sequence passed to uncolor() contains escapes which
1154
+ aren't recognized and can't be translated to names.
1155
+
1156
+ =back
1157
+
1158
+ =head1 ENVIRONMENT
1159
+
1160
+ =over 4
1161
+
1162
+ =item ANSI_COLORS_ALIASES
1163
+
1164
+ This environment variable allows the user to specify custom color aliases
1165
+ that will be understood by color(), colored(), and colorvalid(). None of
1166
+ the other functions will be affected, and no new color constants will be
1167
+ created. The custom colors are aliases for existing color names; no new
1168
+ escape sequences can be introduced. Only alphanumerics, C<.>, C<_>, and
1169
+ C<-> are allowed in alias names.
1170
+
1171
+ The format is:
1172
+
1173
+ ANSI_COLORS_ALIASES='newcolor1=oldcolor1,newcolor2=oldcolor2'
1174
+
1175
+ Whitespace is ignored. The alias value can be a single attribute or a
1176
+ space-separated list of attributes.
1177
+
1178
+ For example the L<Solarized|https://ethanschoonover.com/solarized> colors
1179
+ can be mapped with:
1180
+
1181
+ ANSI_COLORS_ALIASES='\
1182
+ base00=bright_yellow, on_base00=on_bright_yellow,\
1183
+ base01=bright_green, on_base01=on_bright_green, \
1184
+ base02=black, on_base02=on_black, \
1185
+ base03=bright_black, on_base03=on_bright_black, \
1186
+ base0=bright_blue, on_base0=on_bright_blue, \
1187
+ base1=bright_cyan, on_base1=on_bright_cyan, \
1188
+ base2=white, on_base2=on_white, \
1189
+ base3=bright_white, on_base3=on_bright_white, \
1190
+ orange=bright_red, on_orange=on_bright_red, \
1191
+ violet=bright_magenta,on_violet=on_bright_magenta'
1192
+
1193
+ This environment variable is read and applied when the Term::ANSIColor
1194
+ module is loaded and is then subsequently ignored. Changes to
1195
+ ANSI_COLORS_ALIASES after the module is loaded will have no effect. See
1196
+ coloralias() for an equivalent facility that can be used at runtime.
1197
+
1198
+ =item ANSI_COLORS_DISABLED
1199
+
1200
+ If this environment variable is set to a true value, all of the functions
1201
+ defined by this module (color(), colored(), and all of the constants) will not
1202
+ output any escape sequences and instead will just return the empty string or
1203
+ pass through the original text as appropriate. This is intended to support
1204
+ easy use of scripts using this module on platforms that don't support ANSI
1205
+ escape sequences.
1206
+
1207
+ =item NO_COLOR
1208
+
1209
+ If this environment variable is set to any value, it suppresses generation of
1210
+ escape sequences the same as if ANSI_COLORS_DISABLED is set to a true value.
1211
+ This implements the L<https://no-color.org/> informal standard. Programs that
1212
+ want to enable color despite NO_COLOR being set will need to unset that
1213
+ environment variable before any constant or function provided by this module
1214
+ is used.
1215
+
1216
+ =back
1217
+
1218
+ =head1 COMPATIBILITY
1219
+
1220
+ Term::ANSIColor was first included with Perl in Perl 5.6.0.
1221
+
1222
+ The uncolor() function and support for ANSI_COLORS_DISABLED were added in
1223
+ Term::ANSIColor 1.04, included in Perl 5.8.0.
1224
+
1225
+ Support for dark was added in Term::ANSIColor 1.08, included in Perl
1226
+ 5.8.4.
1227
+
1228
+ The color stack, including the C<:pushpop> import tag, PUSHCOLOR,
1229
+ POPCOLOR, LOCALCOLOR, and the $Term::ANSIColor::AUTOLOCAL variable, was
1230
+ added in Term::ANSIColor 2.00, included in Perl 5.10.1.
1231
+
1232
+ colorstrip() was added in Term::ANSIColor 2.01 and colorvalid() was added
1233
+ in Term::ANSIColor 2.02, both included in Perl 5.11.0.
1234
+
1235
+ Support for colors 8 through 15 (the C<bright_> variants) was added in
1236
+ Term::ANSIColor 3.00, included in Perl 5.13.3.
1237
+
1238
+ Support for italic was added in Term::ANSIColor 3.02, included in Perl
1239
+ 5.17.1.
1240
+
1241
+ Support for colors 16 through 256 (the C<ansi>, C<rgb>, and C<grey>
1242
+ colors), the C<:constants256> import tag, the coloralias() function, and
1243
+ support for the ANSI_COLORS_ALIASES environment variable were added in
1244
+ Term::ANSIColor 4.00, included in Perl 5.17.8.
1245
+
1246
+ $Term::ANSIColor::AUTOLOCAL was changed to take precedence over
1247
+ $Term::ANSIColor::AUTORESET, rather than the other way around, in
1248
+ Term::ANSIColor 4.00, included in Perl 5.17.8.
1249
+
1250
+ C<ansi16> through C<ansi255>, as aliases for the C<rgb> and C<grey> colors,
1251
+ and the corresponding C<on_ansi> names and C<ANSI> and C<ON_ANSI> constants
1252
+ were added in Term::ANSIColor 4.06, included in Perl 5.25.7.
1253
+
1254
+ Support for true color (the C<rNNNgNNNbNNN> and C<on_rNNNgNNNbNNN>
1255
+ attributes), defining aliases in terms of other aliases, and aliases mapping
1256
+ to multiple attributes instead of only a single attribute was added in
1257
+ Term::ANSIColor 5.00.
1258
+
1259
+ Support for NO_COLOR was added in Term::ANSIColor 5.01.
1260
+
1261
+ =head1 RESTRICTIONS
1262
+
1263
+ Both colored() and many uses of the color constants will add the reset escape
1264
+ sequence after a newline. If a program mixes colored output to standard
1265
+ output with output to standard error, this can result in the standard error
1266
+ text having the wrong color because the reset escape sequence hasn't yet been
1267
+ flushed to the display (since standard output to a terminal is line-buffered
1268
+ by default). To avoid this, either set autoflush() on STDOUT or set
1269
+ $Term::ANSIColor::EACHLINE to C<"\n">.
1270
+
1271
+ It would be nice if one could leave off the commas around the constants
1272
+ entirely and just say:
1273
+
1274
+ print BOLD BLUE ON_WHITE "Text\n" RESET;
1275
+
1276
+ but the syntax of Perl doesn't allow this. You need a comma after the
1277
+ string. (Of course, you may consider it a bug that commas between all the
1278
+ constants aren't required, in which case you may feel free to insert
1279
+ commas unless you're using $Term::ANSIColor::AUTORESET or
1280
+ PUSHCOLOR/POPCOLOR.)
1281
+
1282
+ For easier debugging, you may prefer to always use the commas when not
1283
+ setting $Term::ANSIColor::AUTORESET or PUSHCOLOR/POPCOLOR so that you'll
1284
+ get a fatal compile error rather than a warning.
1285
+
1286
+ It's not possible to use this module to embed formatting and color
1287
+ attributes using Perl formats. They replace the escape character with a
1288
+ space (as documented in L<perlform(1)>), resulting in garbled output from
1289
+ the unrecognized attribute. Even if there were a way around that problem,
1290
+ the format doesn't know that the non-printing escape sequence is
1291
+ zero-length and would incorrectly format the output. For formatted output
1292
+ using color or other attributes, either use sprintf() instead or use
1293
+ formline() and then add the color or other attributes after formatting and
1294
+ before output.
1295
+
1296
+ =head1 NOTES
1297
+
1298
+ The codes generated by this module are standard terminal control codes,
1299
+ complying with ECMA-048 and ISO 6429 (generally referred to as "ANSI
1300
+ color" for the color codes). The non-color control codes (bold, dark,
1301
+ italic, underline, and reverse) are part of the earlier ANSI X3.64
1302
+ standard for control sequences for video terminals and peripherals.
1303
+
1304
+ Note that not all displays are ISO 6429-compliant, or even X3.64-compliant
1305
+ (or are even attempting to be so). This module will not work as expected
1306
+ on displays that do not honor these escape sequences, such as cmd.exe,
1307
+ 4nt.exe, and command.com under either Windows NT or Windows 2000. They
1308
+ may just be ignored, or they may display as an ESC character followed by
1309
+ some apparent garbage.
1310
+
1311
+ Jean Delvare provided the following table of different common terminal
1312
+ emulators and their support for the various attributes and others have
1313
+ helped me flesh it out:
1314
+
1315
+ clear bold faint under blink reverse conceal
1316
+ ------------------------------------------------------------------------
1317
+ xterm yes yes no yes yes yes yes
1318
+ linux yes yes yes bold yes yes no
1319
+ rxvt yes yes no yes bold/black yes no
1320
+ dtterm yes yes yes yes reverse yes yes
1321
+ teraterm yes reverse no yes rev/red yes no
1322
+ aixterm kinda normal no yes no yes yes
1323
+ PuTTY yes color no yes no yes no
1324
+ Windows yes no no no no yes no
1325
+ Cygwin SSH yes yes no color color color yes
1326
+ Terminal.app yes yes no yes yes yes yes
1327
+
1328
+ Windows is Windows telnet, Cygwin SSH is the OpenSSH implementation under
1329
+ Cygwin on Windows NT, and Mac Terminal is the Terminal application in Mac
1330
+ OS X. Where the entry is other than yes or no, that emulator displays the
1331
+ given attribute as something else instead. Note that on an aixterm, clear
1332
+ doesn't reset colors; you have to explicitly set the colors back to what
1333
+ you want. More entries in this table are welcome.
1334
+
1335
+ Support for code 3 (italic) is rare and therefore not mentioned in that
1336
+ table. It is not believed to be fully supported by any of the terminals
1337
+ listed, although it's displayed as green in the Linux console, but it is
1338
+ reportedly supported by urxvt.
1339
+
1340
+ Note that codes 6 (rapid blink) and 9 (strike-through) are specified in ANSI
1341
+ X3.64 and ECMA-048 but are not commonly supported by most displays and
1342
+ emulators and therefore aren't supported by this module. ECMA-048 also
1343
+ specifies a large number of other attributes, including a sequence of
1344
+ attributes for font changes, Fraktur characters, double-underlining, framing,
1345
+ circling, and overlining. As none of these attributes are widely supported or
1346
+ useful, they also aren't currently supported by this module.
1347
+
1348
+ Most modern X terminal emulators support 256 colors. Known to not support
1349
+ those colors are aterm, rxvt, Terminal.app, and TTY/VC.
1350
+
1351
+ For information on true color support in various terminal emulators, see
1352
+ L<True Colour support|https://gist.github.com/XVilka/8346728>.
1353
+
1354
+ =head1 AUTHORS
1355
+
1356
+ Original idea (using constants) by Zenin, reimplemented using subs by Russ
1357
+ Allbery <rra@cpan.org>, and then combined with the original idea by
1358
+ Russ with input from Zenin. 256-color support is based on work by Kurt
1359
+ Starsinic. Russ Allbery now maintains this module.
1360
+
1361
+ PUSHCOLOR, POPCOLOR, and LOCALCOLOR were contributed by openmethods.com
1362
+ voice solutions.
1363
+
1364
+ =head1 COPYRIGHT AND LICENSE
1365
+
1366
+ Copyright 1996-1998, 2000-2002, 2005-2006, 2008-2018, 2020 Russ Allbery
1367
+ <rra@cpan.org>
1368
+
1369
+ Copyright 1996 Zenin
1370
+
1371
+ Copyright 2012 Kurt Starsinic <kstarsinic@gmail.com>
1372
+
1373
+ This program is free software; you may redistribute it and/or modify it
1374
+ under the same terms as Perl itself.
1375
+
1376
+ =head1 SEE ALSO
1377
+
1378
+ The CPAN module L<Term::ExtendedColor> provides a different and more
1379
+ comprehensive interface for 256-color emulators that may be more
1380
+ convenient. The CPAN module L<Win32::Console::ANSI> provides ANSI color
1381
+ (and other escape sequence) support in the Win32 Console environment.
1382
+ The CPAN module L<Term::Chrome> provides a different interface using
1383
+ objects and operator overloading.
1384
+
1385
+ ECMA-048 is available on-line (at least at the time of this writing) at
1386
+ L<https://www.ecma-international.org/publications/standards/Ecma-048.htm>.
1387
+
1388
+ ISO 6429 is available from ISO for a charge; the author of this module
1389
+ does not own a copy of it. Since the source material for ISO 6429 was
1390
+ ECMA-048 and the latter is available for free, there seems little reason
1391
+ to obtain the ISO standard.
1392
+
1393
+ The 256-color control sequences are documented at
1394
+ L<https://invisible-island.net/xterm/ctlseqs/ctlseqs.html> (search for
1395
+ 256-color).
1396
+
1397
+ Information about true color support in various terminal emulators and test
1398
+ programs you can run to check the true color support in your terminal emulator
1399
+ are available at L<https://gist.github.com/XVilka/8346728>.
1400
+
1401
+ L<CLICOLORS|https://bixense.com/clicolors/> and
1402
+ L<NO_COLOR|https://no-color.org/> are useful standards to be aware of, and
1403
+ ideally follow, for any application using color. Term::ANSIColor complies
1404
+ with the latter.
1405
+
1406
+ The current version of this module is always available from its web site
1407
+ at L<https://www.eyrie.org/~eagle/software/ansicolor/>. It is also part
1408
+ of the Perl core distribution as of 5.6.0.
1409
+
1410
+ =cut
1411
+
1412
+ # Local Variables:
1413
+ # copyright-at-end-flag: t
1414
+ # End:
git/usr/share/perl5/core_perl/Term/Cap.pm ADDED
@@ -0,0 +1,772 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package Term::Cap;
2
+
3
+ # Since the debugger uses Term::ReadLine which uses Term::Cap, we want
4
+ # to load as few modules as possible. This includes Carp.pm.
5
+ sub carp
6
+ {
7
+ require Carp;
8
+ goto &Carp::carp;
9
+ }
10
+
11
+ sub croak
12
+ {
13
+ require Carp;
14
+ goto &Carp::croak;
15
+ }
16
+
17
+ use strict;
18
+
19
+ use vars qw($VERSION $VMS_TERMCAP);
20
+ use vars qw($termpat $state $first $entry);
21
+
22
+ $VERSION = '1.18';
23
+
24
+ # TODO:
25
+ # support Berkeley DB termcaps
26
+ # force $FH into callers package?
27
+ # keep $FH in object at Tgetent time?
28
+
29
+ =head1 NAME
30
+
31
+ Term::Cap - Perl termcap interface
32
+
33
+ =head1 SYNOPSIS
34
+
35
+ require Term::Cap;
36
+ $terminal = Term::Cap->Tgetent({ TERM => undef, OSPEED => $ospeed });
37
+ $terminal->Trequire(qw/ce ku kd/);
38
+ $terminal->Tgoto('cm', $col, $row, $FH);
39
+ $terminal->Tputs('dl', $count, $FH);
40
+ $terminal->Tpad($string, $count, $FH);
41
+
42
+ =head1 DESCRIPTION
43
+
44
+ These are low-level functions to extract and use capabilities from
45
+ a terminal capability (termcap) database.
46
+
47
+ More information on the terminal capabilities will be found in the
48
+ termcap manpage on most Unix-like systems.
49
+
50
+ =head2 METHODS
51
+
52
+ The output strings for B<Tputs> are cached for counts of 1 for performance.
53
+ B<Tgoto> and B<Tpad> do not cache. C<$self-E<gt>{_xx}> is the raw termcap
54
+ data and C<$self-E<gt>{xx}> is the cached version.
55
+
56
+ print $terminal->Tpad($self->{_xx}, 1);
57
+
58
+ B<Tgoto>, B<Tputs>, and B<Tpad> return the string and will also
59
+ output the string to $FH if specified.
60
+
61
+
62
+ =cut
63
+
64
+ # Preload the default VMS termcap.
65
+ # If a different termcap is required then the text of one can be supplied
66
+ # in $Term::Cap::VMS_TERMCAP before Tgetent is called.
67
+
68
+ if ( $^O eq 'VMS' )
69
+ {
70
+ chomp( my @entry = <DATA> );
71
+ $VMS_TERMCAP = join '', @entry;
72
+ }
73
+
74
+ # Returns a list of termcap files to check.
75
+
76
+ sub termcap_path
77
+ { ## private
78
+ my @termcap_path;
79
+
80
+ # $TERMCAP, if it's a filespec
81
+ push( @termcap_path, $ENV{TERMCAP} )
82
+ if (
83
+ ( exists $ENV{TERMCAP} )
84
+ && (
85
+ ( $^O eq 'os2' || $^O eq 'MSWin32' || $^O eq 'dos' )
86
+ ? $ENV{TERMCAP} =~ /^[a-z]:[\\\/]/is
87
+ : $ENV{TERMCAP} =~ /^\//s
88
+ )
89
+ );
90
+ if ( ( exists $ENV{TERMPATH} ) && ( $ENV{TERMPATH} ) )
91
+ {
92
+
93
+ # Add the users $TERMPATH
94
+ push( @termcap_path, split( /:|\s+/, $ENV{TERMPATH} ) );
95
+ }
96
+ else
97
+ {
98
+
99
+ # Defaults
100
+ push( @termcap_path,
101
+ exists $ENV{'HOME'} ? $ENV{'HOME'} . '/.termcap' : undef,
102
+ '/etc/termcap', '/usr/share/misc/termcap', );
103
+ }
104
+
105
+ # return the list of those termcaps that exist
106
+ return grep { defined $_ && -f $_ } @termcap_path;
107
+ }
108
+
109
+ =over 4
110
+
111
+ =item B<Tgetent>
112
+
113
+ Returns a blessed object reference which the user can
114
+ then use to send the control strings to the terminal using B<Tputs>
115
+ and B<Tgoto>.
116
+
117
+ The function extracts the entry of the specified terminal
118
+ type I<TERM> (defaults to the environment variable I<TERM>) from the
119
+ database.
120
+
121
+ It will look in the environment for a I<TERMCAP> variable. If
122
+ found, and the value does not begin with a slash, and the terminal
123
+ type name is the same as the environment string I<TERM>, the
124
+ I<TERMCAP> string is used instead of reading a termcap file. If
125
+ it does begin with a slash, the string is used as a path name of
126
+ the termcap file to search. If I<TERMCAP> does not begin with a
127
+ slash and name is different from I<TERM>, B<Tgetent> searches the
128
+ files F<$HOME/.termcap>, F</etc/termcap>, and F</usr/share/misc/termcap>,
129
+ in that order, unless the environment variable I<TERMPATH> exists,
130
+ in which case it specifies a list of file pathnames (separated by
131
+ spaces or colons) to be searched B<instead>. Whenever multiple
132
+ files are searched and a tc field occurs in the requested entry,
133
+ the entry it names must be found in the same file or one of the
134
+ succeeding files. If there is a C<:tc=...:> in the I<TERMCAP>
135
+ environment variable string it will continue the search in the
136
+ files as above.
137
+
138
+ The extracted termcap entry is available in the object
139
+ as C<$self-E<gt>{TERMCAP}>.
140
+
141
+ It takes a hash reference as an argument with two optional keys:
142
+
143
+ =over 2
144
+
145
+ =item OSPEED
146
+
147
+ The terminal output bit rate (often mistakenly called the baud rate)
148
+ for this terminal - if not set a warning will be generated
149
+ and it will be defaulted to 9600. I<OSPEED> can be specified as
150
+ either a POSIX termios/SYSV termio speeds (where 9600 equals 9600) or
151
+ an old DSD-style speed ( where 13 equals 9600).
152
+
153
+
154
+ =item TERM
155
+
156
+ The terminal type whose termcap entry will be used - if not supplied it will
157
+ default to $ENV{TERM}: if that is not set then B<Tgetent> will croak.
158
+
159
+ =back
160
+
161
+ It calls C<croak> on failure.
162
+
163
+ =cut
164
+
165
+ sub Tgetent
166
+ { ## public -- static method
167
+ my $class = shift;
168
+ my ($self) = @_;
169
+
170
+ $self = {} unless defined $self;
171
+ bless $self, $class;
172
+
173
+ my ( $term, $cap, $search, $field, $max, $tmp_term, $TERMCAP );
174
+ local ( $termpat, $state, $first, $entry ); # used inside eval
175
+ local $_;
176
+
177
+ # Compute PADDING factor from OSPEED (to be used by Tpad)
178
+ if ( !$self->{OSPEED} )
179
+ {
180
+ if ($^W)
181
+ {
182
+ carp "OSPEED was not set, defaulting to 9600";
183
+ }
184
+ $self->{OSPEED} = 9600;
185
+ }
186
+ if ( $self->{OSPEED} < 16 )
187
+ {
188
+
189
+ # delays for old style speeds
190
+ my @pad = (
191
+ 0, 200, 133.3, 90.9, 74.3, 66.7, 50, 33.3,
192
+ 16.7, 8.3, 5.5, 4.1, 2, 1, .5, .2
193
+ );
194
+ $self->{PADDING} = $pad[ $self->{OSPEED} ];
195
+ }
196
+ else
197
+ {
198
+ $self->{PADDING} = 10000 / $self->{OSPEED};
199
+ }
200
+
201
+ unless ( $self->{TERM} )
202
+ {
203
+ if ( $ENV{TERM} )
204
+ {
205
+ $self->{TERM} = $ENV{TERM} ;
206
+ }
207
+ else
208
+ {
209
+ if ( $^O eq 'MSWin32' )
210
+ {
211
+ $self->{TERM} = 'dumb';
212
+ }
213
+ else
214
+ {
215
+ croak "TERM not set";
216
+ }
217
+ }
218
+ }
219
+
220
+ $term = $self->{TERM}; # $term is the term type we are looking for
221
+
222
+ # $tmp_term is always the next term (possibly :tc=...:) we are looking for
223
+ $tmp_term = $self->{TERM};
224
+
225
+ # protect any pattern metacharacters in $tmp_term
226
+ $termpat = $tmp_term;
227
+ $termpat =~ s/(\W)/\\$1/g;
228
+
229
+ my $foo = ( exists $ENV{TERMCAP} ? $ENV{TERMCAP} : '' );
230
+
231
+ # $entry is the extracted termcap entry
232
+ if ( ( $foo !~ m:^/:s ) && ( $foo =~ m/(^|\|)${termpat}[:|]/s ) )
233
+ {
234
+ $entry = $foo;
235
+ }
236
+
237
+ my @termcap_path = termcap_path();
238
+
239
+ if ( !@termcap_path && !$entry )
240
+ {
241
+
242
+ # last resort--fake up a termcap from terminfo
243
+ local $ENV{TERM} = $term;
244
+
245
+ if ( $^O eq 'VMS' )
246
+ {
247
+ $entry = $VMS_TERMCAP;
248
+ }
249
+ else
250
+ {
251
+ if ( grep { -x "$_/infocmp" } split /:/, $ENV{PATH} )
252
+ {
253
+ eval {
254
+ my $tmp = `infocmp -C 2>/dev/null`;
255
+ $tmp =~ s/^#.*\n//gm; # remove comments
256
+ if ( ( $tmp !~ m%^/%s )
257
+ && ( $tmp =~ /(^|\|)${termpat}[:|]/s ) )
258
+ {
259
+ $entry = $tmp;
260
+ }
261
+ };
262
+ warn "Can't run infocmp to get a termcap entry: $@" if $@;
263
+ }
264
+ else
265
+ {
266
+ # this is getting desperate now
267
+ if ( $self->{TERM} eq 'dumb' )
268
+ {
269
+ $entry = 'dumb|80-column dumb tty::am::co#80::bl=^G:cr=^M:do=^J:sf=^J:';
270
+ }
271
+ }
272
+ }
273
+ }
274
+
275
+ croak "Can't find a valid termcap file" unless @termcap_path || $entry;
276
+
277
+ $state = 1; # 0 == finished
278
+ # 1 == next file
279
+ # 2 == search again
280
+
281
+ $first = 0; # first entry (keeps term name)
282
+
283
+ $max = 32; # max :tc=...:'s
284
+
285
+ if ($entry)
286
+ {
287
+
288
+ # ok, we're starting with $TERMCAP
289
+ $first++; # we're the first entry
290
+ # do we need to continue?
291
+ if ( $entry =~ s/:tc=([^:]+):/:/ )
292
+ {
293
+ $tmp_term = $1;
294
+
295
+ # protect any pattern metacharacters in $tmp_term
296
+ $termpat = $tmp_term;
297
+ $termpat =~ s/(\W)/\\$1/g;
298
+ }
299
+ else
300
+ {
301
+ $state = 0; # we're already finished
302
+ }
303
+ }
304
+
305
+ # This is eval'ed inside the while loop for each file
306
+ $search = q{
307
+ while (<TERMCAP>) {
308
+ next if /^\\t/ || /^#/;
309
+ if ($_ =~ m/(^|\\|)${termpat}[:|]/o) {
310
+ chomp;
311
+ s/^[^:]*:// if $first++;
312
+ $state = 0;
313
+ while ($_ =~ s/\\\\$//) {
314
+ defined(my $x = <TERMCAP>) or last;
315
+ $_ .= $x; chomp;
316
+ }
317
+ last;
318
+ }
319
+ }
320
+ defined $entry or $entry = '';
321
+ $entry .= $_ if $_;
322
+ };
323
+
324
+ while ( $state != 0 )
325
+ {
326
+ if ( $state == 1 )
327
+ {
328
+
329
+ # get the next TERMCAP
330
+ $TERMCAP = shift @termcap_path
331
+ || croak "failed termcap lookup on $tmp_term";
332
+ }
333
+ else
334
+ {
335
+
336
+ # do the same file again
337
+ # prevent endless recursion
338
+ $max-- || croak "failed termcap loop at $tmp_term";
339
+ $state = 1; # ok, maybe do a new file next time
340
+ }
341
+
342
+ open( TERMCAP, "< $TERMCAP\0" ) || croak "open $TERMCAP: $!";
343
+ eval $search;
344
+ die $@ if $@;
345
+ close TERMCAP;
346
+
347
+ # If :tc=...: found then search this file again
348
+ $entry =~ s/:tc=([^:]+):/:/ && ( $tmp_term = $1, $state = 2 );
349
+
350
+ # protect any pattern metacharacters in $tmp_term
351
+ $termpat = $tmp_term;
352
+ $termpat =~ s/(\W)/\\$1/g;
353
+ }
354
+
355
+ croak "Can't find $term" if $entry eq '';
356
+ $entry =~ s/:+\s*:+/:/g; # cleanup $entry
357
+ $entry =~ s/:+/:/g; # cleanup $entry
358
+ $self->{TERMCAP} = $entry; # save it
359
+ # print STDERR "DEBUG: $entry = ", $entry, "\n";
360
+
361
+ # Precompile $entry into the object
362
+ $entry =~ s/^[^:]*://;
363
+ foreach $field ( split( /:[\s:\\]*/, $entry ) )
364
+ {
365
+ if ( defined $field && $field =~ /^(\w{2,})$/ )
366
+ {
367
+ $self->{ '_' . $field } = 1 unless defined $self->{ '_' . $1 };
368
+
369
+ # print STDERR "DEBUG: flag $1\n";
370
+ }
371
+ elsif ( defined $field && $field =~ /^(\w{2,})\@/ )
372
+ {
373
+ $self->{ '_' . $1 } = "";
374
+
375
+ # print STDERR "DEBUG: unset $1\n";
376
+ }
377
+ elsif ( defined $field && $field =~ /^(\w{2,})#(.*)/ )
378
+ {
379
+ $self->{ '_' . $1 } = $2 unless defined $self->{ '_' . $1 };
380
+
381
+ # print STDERR "DEBUG: numeric $1 = $2\n";
382
+ }
383
+ elsif ( defined $field && $field =~ /^(\w{2,})=(.*)/ )
384
+ {
385
+
386
+ # print STDERR "DEBUG: string $1 = $2\n";
387
+ next if defined $self->{ '_' . ( $cap = $1 ) };
388
+ $_ = $2;
389
+ if ( ord('A') == 193 )
390
+ {
391
+ s/\\E/\047/g;
392
+ s/\\(\d\d\d)/pack('c',oct($1) & 0177)/eg;
393
+ s/\\n/\n/g;
394
+ s/\\r/\r/g;
395
+ s/\\t/\t/g;
396
+ s/\\b/\b/g;
397
+ s/\\f/\f/g;
398
+ s/\\\^/\337/g;
399
+ s/\^\?/\007/g;
400
+ s/\^(.)/pack('c',ord($1) & 31)/eg;
401
+ s/\\(.)/$1/g;
402
+ s/\337/^/g;
403
+ }
404
+ else
405
+ {
406
+ s/\\E/\033/g;
407
+ s/\\(\d\d\d)/pack('c',oct($1) & 0177)/eg;
408
+ s/\\n/\n/g;
409
+ s/\\r/\r/g;
410
+ s/\\t/\t/g;
411
+ s/\\b/\b/g;
412
+ s/\\f/\f/g;
413
+ s/\\\^/\377/g;
414
+ s/\^\?/\177/g;
415
+ s/\^(.)/pack('c',ord($1) & 31)/eg;
416
+ s/\\(.)/$1/g;
417
+ s/\377/^/g;
418
+ }
419
+ $self->{ '_' . $cap } = $_;
420
+ }
421
+
422
+ # else { carp "junk in $term ignored: $field"; }
423
+ }
424
+ $self->{'_pc'} = "\0" unless defined $self->{'_pc'};
425
+ $self->{'_bc'} = "\b" unless defined $self->{'_bc'};
426
+ $self;
427
+ }
428
+
429
+ # $terminal->Tpad($string, $cnt, $FH);
430
+
431
+ =item B<Tpad>
432
+
433
+ Outputs a literal string with appropriate padding for the current terminal.
434
+
435
+ It takes three arguments:
436
+
437
+ =over 2
438
+
439
+ =item B<$string>
440
+
441
+ The literal string to be output. If it starts with a number and an optional
442
+ '*' then the padding will be increased by an amount relative to this number,
443
+ if the '*' is present then this amount will be multiplied by $cnt. This part
444
+ of $string is removed before output/
445
+
446
+ =item B<$cnt>
447
+
448
+ Will be used to modify the padding applied to string as described above.
449
+
450
+ =item B<$FH>
451
+
452
+ An optional filehandle (or IO::Handle ) that output will be printed to.
453
+
454
+ =back
455
+
456
+ The padded $string is returned.
457
+
458
+ =cut
459
+
460
+ sub Tpad
461
+ { ## public
462
+ my $self = shift;
463
+ my ( $string, $cnt, $FH ) = @_;
464
+ my ( $decr, $ms );
465
+
466
+ if ( defined $string && $string =~ /(^[\d.]+)(\*?)(.*)$/ )
467
+ {
468
+ $ms = $1;
469
+ $ms *= $cnt if $2;
470
+ $string = $3;
471
+ $decr = $self->{PADDING};
472
+ if ( $decr > .1 )
473
+ {
474
+ $ms += $decr / 2;
475
+ $string .= $self->{'_pc'} x ( $ms / $decr );
476
+ }
477
+ }
478
+ print $FH $string if $FH;
479
+ $string;
480
+ }
481
+
482
+ # $terminal->Tputs($cap, $cnt, $FH);
483
+
484
+ =item B<Tputs>
485
+
486
+ Output the string for the given capability padded as appropriate without
487
+ any parameter substitution.
488
+
489
+ It takes three arguments:
490
+
491
+ =over 2
492
+
493
+ =item B<$cap>
494
+
495
+ The capability whose string is to be output.
496
+
497
+ =item B<$cnt>
498
+
499
+ A count passed to Tpad to modify the padding applied to the output string.
500
+ If $cnt is zero or one then the resulting string will be cached.
501
+
502
+ =item B<$FH>
503
+
504
+ An optional filehandle (or IO::Handle ) that output will be printed to.
505
+
506
+ =back
507
+
508
+ The appropriate string for the capability will be returned.
509
+
510
+ =cut
511
+
512
+ sub Tputs
513
+ { ## public
514
+ my $self = shift;
515
+ my ( $cap, $cnt, $FH ) = @_;
516
+ my $string;
517
+
518
+ $cnt = 0 unless $cnt;
519
+
520
+ if ( $cnt > 1 )
521
+ {
522
+ $string = Tpad( $self, $self->{ '_' . $cap }, $cnt );
523
+ }
524
+ else
525
+ {
526
+
527
+ # cache result because Tpad can be slow
528
+ unless ( exists $self->{$cap} )
529
+ {
530
+ $self->{$cap} =
531
+ exists $self->{"_$cap"}
532
+ ? Tpad( $self, $self->{"_$cap"}, 1 )
533
+ : undef;
534
+ }
535
+ $string = $self->{$cap};
536
+ }
537
+ print $FH $string if $FH;
538
+ $string;
539
+ }
540
+
541
+ # $terminal->Tgoto($cap, $col, $row, $FH);
542
+
543
+ =item B<Tgoto>
544
+
545
+ B<Tgoto> decodes a cursor addressing string with the given parameters.
546
+
547
+ There are four arguments:
548
+
549
+ =over 2
550
+
551
+ =item B<$cap>
552
+
553
+ The name of the capability to be output.
554
+
555
+ =item B<$col>
556
+
557
+ The first value to be substituted in the output string ( usually the column
558
+ in a cursor addressing capability )
559
+
560
+ =item B<$row>
561
+
562
+ The second value to be substituted in the output string (usually the row
563
+ in cursor addressing capabilities)
564
+
565
+ =item B<$FH>
566
+
567
+ An optional filehandle (or IO::Handle ) to which the output string will be
568
+ printed.
569
+
570
+ =back
571
+
572
+ Substitutions are made with $col and $row in the output string with the
573
+ following sprintf() line formats:
574
+
575
+ %% output `%'
576
+ %d output value as in printf %d
577
+ %2 output value as in printf %2d
578
+ %3 output value as in printf %3d
579
+ %. output value as in printf %c
580
+ %+x add x to value, then do %.
581
+
582
+ %>xy if value > x then add y, no output
583
+ %r reverse order of two parameters, no output
584
+ %i increment by one, no output
585
+ %B BCD (16*(value/10)) + (value%10), no output
586
+
587
+ %n exclusive-or all parameters with 0140 (Datamedia 2500)
588
+ %D Reverse coding (value - 2*(value%16)), no output (Delta Data)
589
+
590
+ The output string will be returned.
591
+
592
+ =cut
593
+
594
+ sub Tgoto
595
+ { ## public
596
+ my $self = shift;
597
+ my ( $cap, $code, $tmp, $FH ) = @_;
598
+ my $string = $self->{ '_' . $cap };
599
+ my $result = '';
600
+ my $after = '';
601
+ my $online = 0;
602
+ my @tmp = ( $tmp, $code );
603
+ my $cnt = $code;
604
+
605
+ while ( $string =~ /^([^%]*)%(.)(.*)/ )
606
+ {
607
+ $result .= $1;
608
+ $code = $2;
609
+ $string = $3;
610
+ if ( $code eq 'd' )
611
+ {
612
+ $result .= sprintf( "%d", shift(@tmp) );
613
+ }
614
+ elsif ( $code eq '.' )
615
+ {
616
+ $tmp = shift(@tmp);
617
+ if ( $tmp == 0 || $tmp == 4 || $tmp == 10 )
618
+ {
619
+ if ($online)
620
+ {
621
+ ++$tmp, $after .= $self->{'_up'} if $self->{'_up'};
622
+ }
623
+ else
624
+ {
625
+ ++$tmp, $after .= $self->{'_bc'};
626
+ }
627
+ }
628
+ $result .= sprintf( "%c", $tmp );
629
+ $online = !$online;
630
+ }
631
+ elsif ( $code eq '+' )
632
+ {
633
+ $result .= sprintf( "%c", shift(@tmp) + ord($string) );
634
+ $string = substr( $string, 1, 99 );
635
+ $online = !$online;
636
+ }
637
+ elsif ( $code eq 'r' )
638
+ {
639
+ ( $code, $tmp ) = @tmp;
640
+ @tmp = ( $tmp, $code );
641
+ $online = !$online;
642
+ }
643
+ elsif ( $code eq '>' )
644
+ {
645
+ ( $code, $tmp, $string ) = unpack( "CCa99", $string );
646
+ if ( $tmp[0] > $code )
647
+ {
648
+ $tmp[0] += $tmp;
649
+ }
650
+ }
651
+ elsif ( $code eq '2' )
652
+ {
653
+ $result .= sprintf( "%02d", shift(@tmp) );
654
+ $online = !$online;
655
+ }
656
+ elsif ( $code eq '3' )
657
+ {
658
+ $result .= sprintf( "%03d", shift(@tmp) );
659
+ $online = !$online;
660
+ }
661
+ elsif ( $code eq 'i' )
662
+ {
663
+ ( $code, $tmp ) = @tmp;
664
+ @tmp = ( $code + 1, $tmp + 1 );
665
+ }
666
+ else
667
+ {
668
+ return "OOPS";
669
+ }
670
+ }
671
+ $string = Tpad( $self, $result . $string . $after, $cnt );
672
+ print $FH $string if $FH;
673
+ $string;
674
+ }
675
+
676
+ # $terminal->Trequire(qw/ce ku kd/);
677
+
678
+ =item B<Trequire>
679
+
680
+ Takes a list of capabilities as an argument and will croak if one is not
681
+ found.
682
+
683
+ =cut
684
+
685
+ sub Trequire
686
+ { ## public
687
+ my $self = shift;
688
+ my ( $cap, @undefined );
689
+ foreach $cap (@_)
690
+ {
691
+ push( @undefined, $cap )
692
+ unless defined $self->{ '_' . $cap } && $self->{ '_' . $cap };
693
+ }
694
+ croak "Terminal does not support: (@undefined)" if @undefined;
695
+ }
696
+
697
+ =back
698
+
699
+ =head1 EXAMPLES
700
+
701
+ use Term::Cap;
702
+
703
+ # Get terminal output speed
704
+ require POSIX;
705
+ my $termios = POSIX::Termios->new;
706
+ $termios->getattr;
707
+ my $ospeed = $termios->getospeed;
708
+
709
+ # Old-style ioctl code to get ospeed:
710
+ # require 'ioctl.pl';
711
+ # ioctl(TTY,$TIOCGETP,$sgtty);
712
+ # ($ispeed,$ospeed) = unpack('cc',$sgtty);
713
+
714
+ # allocate and initialize a terminal structure
715
+ my $terminal = Term::Cap->Tgetent({ TERM => undef, OSPEED => $ospeed });
716
+
717
+ # require certain capabilities to be available
718
+ $terminal->Trequire(qw/ce ku kd/);
719
+
720
+ # Output Routines, if $FH is undefined these just return the string
721
+
722
+ # Tgoto does the % expansion stuff with the given args
723
+ $terminal->Tgoto('cm', $col, $row, $FH);
724
+
725
+ # Tputs doesn't do any % expansion.
726
+ $terminal->Tputs('dl', $count = 1, $FH);
727
+
728
+ =head1 COPYRIGHT AND LICENSE
729
+
730
+ Copyright 1995-2015 (c) perl5 porters.
731
+
732
+ This software is free software and can be modified and distributed under
733
+ the same terms as Perl itself.
734
+
735
+ Please see the file README in the Perl source distribution for details of
736
+ the Perl license.
737
+
738
+ =head1 AUTHOR
739
+
740
+ This module is part of the core Perl distribution and is also maintained
741
+ for CPAN by Jonathan Stowe <jns@gellyfish.co.uk>.
742
+
743
+ The code is hosted on Github: https://github.com/jonathanstowe/Term-Cap
744
+ please feel free to fork, submit patches etc, etc there.
745
+
746
+ =head1 SEE ALSO
747
+
748
+ termcap(5)
749
+
750
+ =cut
751
+
752
+ # Below is a default entry for systems where there are terminals but no
753
+ # termcap
754
+ 1;
755
+ __DATA__
756
+ vt220|vt200|DEC VT220 in vt100 emulation mode:
757
+ am:mi:xn:xo:
758
+ co#80:li#24:
759
+ RA=\E[?7l:SA=\E[?7h:
760
+ ac=kkllmmjjnnwwqquuttvvxx:ae=\E(B:al=\E[L:as=\E(0:
761
+ bl=^G:cd=\E[J:ce=\E[K:cl=\E[H\E[2J:cm=\E[%i%d;%dH:
762
+ cr=^M:cs=\E[%i%d;%dr:dc=\E[P:dl=\E[M:do=\E[B:
763
+ ei=\E[4l:ho=\E[H:im=\E[4h:
764
+ is=\E[1;24r\E[24;1H:
765
+ nd=\E[C:
766
+ kd=\E[B::kl=\E[D:kr=\E[C:ku=\E[A:le=^H:
767
+ mb=\E[5m:md=\E[1m:me=\E[m:mr=\E[7m:
768
+ kb=\0177:
769
+ r2=\E>\E[24;1H\E[?3l\E[?4l\E[?5l\E[?7h\E[?8h\E=:rc=\E8:
770
+ sc=\E7:se=\E[27m:sf=\ED:so=\E[7m:sr=\EM:ta=^I:
771
+ ue=\E[24m:up=\E[A:us=\E[4m:ve=\E[?25h:vi=\E[?25l:
772
+
git/usr/share/perl5/core_perl/Term/Complete.pm ADDED
@@ -0,0 +1,188 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package Term::Complete;
2
+ require 5.000;
3
+ require Exporter;
4
+
5
+ use strict;
6
+ our @ISA = qw(Exporter);
7
+ our @EXPORT = qw(Complete);
8
+ our $VERSION = '1.403';
9
+
10
+ # @(#)complete.pl,v1.2 (me@anywhere.EBay.Sun.COM) 09/23/91
11
+
12
+ =head1 NAME
13
+
14
+ Term::Complete - Perl word completion module
15
+
16
+ =head1 SYNOPSIS
17
+
18
+ $input = Complete('prompt_string', \@completion_list);
19
+ $input = Complete('prompt_string', @completion_list);
20
+
21
+ =head1 DESCRIPTION
22
+
23
+ This routine provides word completion on the list of words in
24
+ the array (or array ref).
25
+
26
+ The tty driver is put into raw mode and restored using an operating
27
+ system specific command, in UNIX-like environments C<stty>.
28
+
29
+ The following command characters are defined:
30
+
31
+ =over 4
32
+
33
+ =item E<lt>tabE<gt>
34
+
35
+ Attempts word completion.
36
+ Cannot be changed.
37
+
38
+ =item ^D
39
+
40
+ Prints completion list.
41
+ Defined by I<$Term::Complete::complete>.
42
+
43
+ =item ^U
44
+
45
+ Erases the current input.
46
+ Defined by I<$Term::Complete::kill>.
47
+
48
+ =item E<lt>delE<gt>, E<lt>bsE<gt>
49
+
50
+ Erases one character.
51
+ Defined by I<$Term::Complete::erase1> and I<$Term::Complete::erase2>.
52
+
53
+ =back
54
+
55
+ =head1 DIAGNOSTICS
56
+
57
+ Bell sounds when word completion fails.
58
+
59
+ =head1 BUGS
60
+
61
+ The completion character E<lt>tabE<gt> cannot be changed.
62
+
63
+ =head1 AUTHOR
64
+
65
+ Wayne Thompson
66
+
67
+ =cut
68
+
69
+ our($complete, $kill, $erase1, $erase2, $tty_raw_noecho, $tty_restore, $stty, $tty_safe_restore);
70
+ our($tty_saved_state) = '';
71
+ CONFIG: {
72
+ $complete = "\004";
73
+ $kill = "\025";
74
+ $erase1 = "\177";
75
+ $erase2 = "\010";
76
+ foreach my $s (qw(/bin/stty /usr/bin/stty)) {
77
+ if (-x $s) {
78
+ $tty_raw_noecho = "$s raw -echo";
79
+ $tty_restore = "$s -raw echo";
80
+ $tty_safe_restore = $tty_restore;
81
+ $stty = $s;
82
+ last;
83
+ }
84
+ }
85
+ }
86
+
87
+ sub Complete {
88
+ my($prompt, @cmp_lst, $cmp, $test, $l, @match);
89
+ my ($return, $r) = ("", 0);
90
+
91
+ $return = "";
92
+ $r = 0;
93
+
94
+ $prompt = shift;
95
+ if (ref $_[0] || $_[0] =~ /^\*/) {
96
+ @cmp_lst = sort @{$_[0]};
97
+ }
98
+ else {
99
+ @cmp_lst = sort(@_);
100
+ }
101
+
102
+ # Attempt to save the current stty state, to be restored later
103
+ if (defined $stty && defined $tty_saved_state && $tty_saved_state eq '') {
104
+ $tty_saved_state = qx($stty -g 2>/dev/null);
105
+ if ($?) {
106
+ # stty -g not supported
107
+ $tty_saved_state = undef;
108
+ }
109
+ else {
110
+ $tty_saved_state =~ s/\s+$//g;
111
+ $tty_restore = qq($stty "$tty_saved_state" 2>/dev/null);
112
+ }
113
+ }
114
+ system $tty_raw_noecho if defined $tty_raw_noecho;
115
+ LOOP: {
116
+ local $_;
117
+ print($prompt, $return);
118
+ while (($_ = getc(STDIN)) ne "\r") {
119
+ CASE: {
120
+ # (TAB) attempt completion
121
+ $_ eq "\t" && do {
122
+ @match = grep(/^\Q$return/, @cmp_lst);
123
+ unless ($#match < 0) {
124
+ $l = length($test = shift(@match));
125
+ foreach $cmp (@match) {
126
+ until (substr($cmp, 0, $l) eq substr($test, 0, $l)) {
127
+ $l--;
128
+ }
129
+ }
130
+ print("\a");
131
+ print($test = substr($test, $r, $l - $r));
132
+ $r = length($return .= $test);
133
+ }
134
+ last CASE;
135
+ };
136
+
137
+ # (^D) completion list
138
+ $_ eq $complete && do {
139
+ print(join("\r\n", '', grep(/^\Q$return/, @cmp_lst)), "\r\n");
140
+ redo LOOP;
141
+ };
142
+
143
+ # (^U) kill
144
+ $_ eq $kill && do {
145
+ if ($r) {
146
+ $r = 0;
147
+ $return = "";
148
+ print("\r\n");
149
+ redo LOOP;
150
+ }
151
+ last CASE;
152
+ };
153
+
154
+ # (DEL) || (BS) erase
155
+ ($_ eq $erase1 || $_ eq $erase2) && do {
156
+ if($r) {
157
+ print("\b \b");
158
+ chop($return);
159
+ $r--;
160
+ }
161
+ last CASE;
162
+ };
163
+
164
+ # printable char
165
+ ord >= ord(" ") && do {
166
+ $return .= $_;
167
+ $r++;
168
+ print;
169
+ last CASE;
170
+ };
171
+ }
172
+ }
173
+ }
174
+
175
+ # system $tty_restore if defined $tty_restore;
176
+ if (defined $tty_saved_state && defined $tty_restore && defined $tty_safe_restore)
177
+ {
178
+ system $tty_restore;
179
+ if ($?) {
180
+ # tty_restore caused error
181
+ system $tty_safe_restore;
182
+ }
183
+ }
184
+ print("\n");
185
+ $return;
186
+ }
187
+
188
+ 1;
git/usr/share/perl5/core_perl/Term/ReadLine.pm ADDED
@@ -0,0 +1,487 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ =head1 NAME
2
+
3
+ Term::ReadLine - Perl interface to various C<readline> packages.
4
+ If no real package is found, substitutes stubs instead of basic functions.
5
+
6
+ =head1 SYNOPSIS
7
+
8
+ use Term::ReadLine;
9
+ my $term = Term::ReadLine->new('Simple Perl calc');
10
+ my $prompt = "Enter your arithmetic expression: ";
11
+ my $OUT = $term->OUT || \*STDOUT;
12
+ while ( defined ($_ = $term->readline($prompt)) ) {
13
+ my $res = eval($_);
14
+ warn $@ if $@;
15
+ print $OUT $res, "\n" unless $@;
16
+ $term->addhistory($_) if /\S/;
17
+ }
18
+
19
+ =head1 DESCRIPTION
20
+
21
+ This package is just a front end to some other packages. It's a stub to
22
+ set up a common interface to the various ReadLine implementations found on
23
+ CPAN (under the C<Term::ReadLine::*> namespace).
24
+
25
+ =head1 Minimal set of supported functions
26
+
27
+ All the supported functions should be called as methods, i.e., either as
28
+
29
+ $term = Term::ReadLine->new('name');
30
+
31
+ or as
32
+
33
+ $term->addhistory('row');
34
+
35
+ where $term is a return value of Term::ReadLine-E<gt>new().
36
+
37
+ =over 12
38
+
39
+ =item C<ReadLine>
40
+
41
+ returns the actual package that executes the commands. Among possible
42
+ values are C<Term::ReadLine::Gnu>, C<Term::ReadLine::Perl>,
43
+ C<Term::ReadLine::Stub>.
44
+
45
+ =item C<new>
46
+
47
+ returns the handle for subsequent calls to following
48
+ functions. Argument is the name of the application. Optionally can be
49
+ followed by two arguments for C<IN> and C<OUT> filehandles. These
50
+ arguments should be globs.
51
+
52
+ =item C<readline>
53
+
54
+ gets an input line, I<possibly> with actual C<readline>
55
+ support. Trailing newline is removed. Returns C<undef> on C<EOF>.
56
+
57
+ =item C<addhistory>
58
+
59
+ adds the line to the history of input, from where it can be used if
60
+ the actual C<readline> is present.
61
+
62
+ =item C<IN>, C<OUT>
63
+
64
+ return the filehandles for input and output or C<undef> if C<readline>
65
+ input and output cannot be used for Perl.
66
+
67
+ =item C<MinLine>
68
+
69
+ If argument is specified, it is an advice on minimal size of line to
70
+ be included into history. C<undef> means do not include anything into
71
+ history. Returns the old value.
72
+
73
+ =item C<findConsole>
74
+
75
+ returns an array with two strings that give most appropriate names for
76
+ files for input and output using conventions C<"E<lt>$in">, C<"E<gt>out">.
77
+
78
+ The strings returned may not be useful for 3-argument open().
79
+
80
+ =item Attribs
81
+
82
+ returns a reference to a hash which describes internal configuration
83
+ of the package. Names of keys in this hash conform to standard
84
+ conventions with the leading C<rl_> stripped.
85
+
86
+ =item C<Features>
87
+
88
+ Returns a reference to a hash with keys being features present in
89
+ current implementation. Several optional features are used in the
90
+ minimal interface: C<appname> should be present if the first argument
91
+ to C<new> is recognized, and C<minline> should be present if
92
+ C<MinLine> method is not dummy. C<autohistory> should be present if
93
+ lines are put into history automatically (maybe subject to
94
+ C<MinLine>), and C<addhistory> if C<addhistory> method is not dummy.
95
+
96
+ If C<Features> method reports a feature C<attribs> as present, the
97
+ method C<Attribs> is not dummy.
98
+
99
+ =back
100
+
101
+ =head1 Additional supported functions
102
+
103
+ Actually C<Term::ReadLine> can use some other package, that will
104
+ support a richer set of commands.
105
+
106
+ All these commands are callable via method interface and have names
107
+ which conform to standard conventions with the leading C<rl_> stripped.
108
+
109
+ The stub package included with the perl distribution allows some
110
+ additional methods:
111
+
112
+ =over 12
113
+
114
+ =item C<tkRunning>
115
+
116
+ makes Tk event loop run when waiting for user input (i.e., during
117
+ C<readline> method).
118
+
119
+ =item C<event_loop>
120
+
121
+ Registers call-backs to wait for user input (i.e., during C<readline>
122
+ method). This supersedes tkRunning.
123
+
124
+ The first call-back registered is the call back for waiting. It is
125
+ expected that the callback will call the current event loop until
126
+ there is something waiting to get on the input filehandle. The parameter
127
+ passed in is the return value of the second call back.
128
+
129
+ The second call-back registered is the call back for registration. The
130
+ input filehandle (often STDIN, but not necessarily) will be passed in.
131
+
132
+ For example, with AnyEvent:
133
+
134
+ $term->event_loop(sub {
135
+ my $data = shift;
136
+ $data->[1] = AE::cv();
137
+ $data->[1]->recv();
138
+ }, sub {
139
+ my $fh = shift;
140
+ my $data = [];
141
+ $data->[0] = AE::io($fh, 0, sub { $data->[1]->send() });
142
+ $data;
143
+ });
144
+
145
+ The second call-back is optional if the call back is registered prior to
146
+ the call to $term-E<gt>readline.
147
+
148
+ Deregistration is done in this case by calling event_loop with C<undef>
149
+ as its parameter:
150
+
151
+ $term->event_loop(undef);
152
+
153
+ This will cause the data array ref to be removed, allowing normal garbage
154
+ collection to clean it up. With AnyEvent, that will cause $data->[0] to
155
+ be cleaned up, and AnyEvent will automatically cancel the watcher at that
156
+ time. If another loop requires more than that to clean up a file watcher,
157
+ that will be up to the caller to handle.
158
+
159
+ =item C<ornaments>
160
+
161
+ makes the command line stand out by using termcap data. The argument
162
+ to C<ornaments> should be 0, 1, or a string of a form
163
+ C<"aa,bb,cc,dd">. Four components of this string should be names of
164
+ I<terminal capacities>, first two will be issued to make the prompt
165
+ standout, last two to make the input line standout.
166
+
167
+ =item C<newTTY>
168
+
169
+ takes two arguments which are input filehandle and output filehandle.
170
+ Switches to use these filehandles.
171
+
172
+ =back
173
+
174
+ One can check whether the currently loaded ReadLine package supports
175
+ these methods by checking for corresponding C<Features>.
176
+
177
+ =head1 EXPORTS
178
+
179
+ None
180
+
181
+ =head1 ENVIRONMENT
182
+
183
+ The environment variable C<PERL_RL> governs which ReadLine clone is
184
+ loaded. If the value is false, a dummy interface is used. If the value
185
+ is true, it should be tail of the name of the package to use, such as
186
+ C<Perl> or C<Gnu>.
187
+
188
+ As a special case, if the value of this variable is space-separated,
189
+ the tail might be used to disable the ornaments by setting the tail to
190
+ be C<o=0> or C<ornaments=0>. The head should be as described above, say
191
+
192
+ If the variable is not set, or if the head of space-separated list is
193
+ empty, the best available package is loaded.
194
+
195
+ export "PERL_RL=Perl o=0" # Use Perl ReadLine sans ornaments
196
+ export "PERL_RL= o=0" # Use best available ReadLine sans ornaments
197
+
198
+ (Note that processing of C<PERL_RL> for ornaments is in the discretion of the
199
+ particular used C<Term::ReadLine::*> package).
200
+
201
+ =cut
202
+
203
+ use strict;
204
+
205
+ package Term::ReadLine::Stub;
206
+ our @ISA = qw'Term::ReadLine::Tk Term::ReadLine::TermCap';
207
+
208
+ $DB::emacs = $DB::emacs; # To pacify -w
209
+ our @rl_term_set;
210
+ *rl_term_set = \@Term::ReadLine::TermCap::rl_term_set;
211
+
212
+ sub PERL_UNICODE_STDIN () { 0x0001 }
213
+
214
+ sub ReadLine {'Term::ReadLine::Stub'}
215
+ sub readline {
216
+ my $self = shift;
217
+ my ($in,$out,$str) = @$self;
218
+ my $prompt = shift;
219
+ print $out $rl_term_set[0], $prompt, $rl_term_set[1], $rl_term_set[2];
220
+ $self->register_Tk
221
+ if not $Term::ReadLine::registered and $Term::ReadLine::toloop;
222
+ #$str = scalar <$in>;
223
+ $str = $self->get_line;
224
+ utf8::upgrade($str)
225
+ if (${^UNICODE} & PERL_UNICODE_STDIN || defined ${^ENCODING}) &&
226
+ utf8::valid($str);
227
+ print $out $rl_term_set[3];
228
+ # bug in 5.000: chomping empty string creates length -1:
229
+ chomp $str if defined $str;
230
+ $str;
231
+ }
232
+ sub addhistory {}
233
+
234
+ # used for testing purpose
235
+ sub devtty { return '/dev/tty' }
236
+
237
+ sub findConsole {
238
+ my $console;
239
+ my $consoleOUT;
240
+
241
+ my $devtty = devtty();
242
+
243
+ if ($^O ne 'MSWin32' and -e $devtty) {
244
+ $console = $devtty;
245
+ } elsif ($^O eq 'MSWin32' or $^O eq 'msys' or -e "con") {
246
+ $console = 'CONIN$';
247
+ $consoleOUT = 'CONOUT$';
248
+ } elsif ($^O eq 'VMS') {
249
+ $console = "sys\$command";
250
+ } elsif ($^O eq 'os2' && !$DB::emacs) {
251
+ $console = "/dev/con";
252
+ } else {
253
+ $console = undef;
254
+ }
255
+
256
+ $consoleOUT = $console unless defined $consoleOUT;
257
+ $console = "&STDIN" unless defined $console;
258
+ if ($console eq $devtty && !open(my $fh, "<", $console)) {
259
+ $console = "&STDIN";
260
+ undef($consoleOUT);
261
+ }
262
+ if (!defined $consoleOUT) {
263
+ $consoleOUT = defined fileno(STDERR) && $^O ne 'MSWin32' ? "&STDERR" : "&STDOUT";
264
+ }
265
+ ($console,$consoleOUT);
266
+ }
267
+
268
+ sub new {
269
+ die "method new called with wrong number of arguments"
270
+ unless @_==2 or @_==4;
271
+ #local (*FIN, *FOUT);
272
+ my ($FIN, $FOUT, $ret);
273
+ if (@_==2) {
274
+ my($console, $consoleOUT) = $_[0]->findConsole;
275
+
276
+ # the Windows CONIN$ needs GENERIC_WRITE mode to allow
277
+ # a SetConsoleMode() if we end up using Term::ReadKey
278
+ open FIN, (( $^O eq 'MSWin32' && $console eq 'CONIN$' ) ? '+<' : '<' ), $console;
279
+ # RT #132008: Still need 2-arg open here
280
+ open FOUT,">$consoleOUT";
281
+
282
+ #OUT->autoflush(1); # Conflicts with debugger?
283
+ my $sel = select(FOUT);
284
+ $| = 1; # for DB::OUT
285
+ select($sel);
286
+ $ret = bless [\*FIN, \*FOUT];
287
+ } else { # Filehandles supplied
288
+ $FIN = $_[2]; $FOUT = $_[3];
289
+ #OUT->autoflush(1); # Conflicts with debugger?
290
+ my $sel = select($FOUT);
291
+ $| = 1; # for DB::OUT
292
+ select($sel);
293
+ $ret = bless [$FIN, $FOUT];
294
+ }
295
+ if ($ret->Features->{ornaments}
296
+ and not ($ENV{PERL_RL} and $ENV{PERL_RL} =~ /\bo\w*=0/)) {
297
+ local $Term::ReadLine::termcap_nowarn = 1;
298
+ $ret->ornaments(1);
299
+ }
300
+ return $ret;
301
+ }
302
+
303
+ sub newTTY {
304
+ my ($self, $in, $out) = @_;
305
+ $self->[0] = $in;
306
+ $self->[1] = $out;
307
+ my $sel = select($out);
308
+ $| = 1; # for DB::OUT
309
+ select($sel);
310
+ }
311
+
312
+ sub IN { shift->[0] }
313
+ sub OUT { shift->[1] }
314
+ sub MinLine { undef }
315
+ sub Attribs { {} }
316
+
317
+ my %features = (tkRunning => 1, ornaments => 1, 'newTTY' => 1);
318
+ sub Features { \%features }
319
+
320
+ #sub get_line {
321
+ # my $self = shift;
322
+ # my $in = $self->IN;
323
+ # local ($/) = "\n";
324
+ # return scalar <$in>;
325
+ #}
326
+
327
+ package Term::ReadLine; # So late to allow the above code be defined?
328
+
329
+ our $VERSION = '1.17';
330
+
331
+ my ($which) = exists $ENV{PERL_RL} ? split /\s+/, $ENV{PERL_RL} : undef;
332
+ if ($which) {
333
+ if ($which =~ /\bgnu\b/i){
334
+ eval "use Term::ReadLine::Gnu;";
335
+ } elsif ($which =~ /\bperl\b/i) {
336
+ eval "use Term::ReadLine::Perl;";
337
+ } elsif ($which =~ /^(Stub|TermCap|Tk)$/) {
338
+ # it is already in memory to avoid false exception as seen in:
339
+ # PERL_RL=Stub perl -e'$SIG{__DIE__} = sub { print @_ }; require Term::ReadLine'
340
+ } else {
341
+ eval "use Term::ReadLine::$which;";
342
+ }
343
+ } elsif (defined $which and $which ne '') { # Defined but false
344
+ # Do nothing fancy
345
+ } else {
346
+ eval "use Term::ReadLine::Gnu; 1" or eval "use Term::ReadLine::EditLine; 1" or eval "use Term::ReadLine::Perl; 1";
347
+ }
348
+
349
+ #require FileHandle;
350
+
351
+ # To make possible switch off RL in debugger: (Not needed, work done
352
+ # in debugger).
353
+ our @ISA;
354
+ if (defined &Term::ReadLine::Gnu::readline) {
355
+ @ISA = qw(Term::ReadLine::Gnu Term::ReadLine::Stub);
356
+ } elsif (defined &Term::ReadLine::EditLine::readline) {
357
+ @ISA = qw(Term::ReadLine::EditLine Term::ReadLine::Stub);
358
+ } elsif (defined &Term::ReadLine::Perl::readline) {
359
+ @ISA = qw(Term::ReadLine::Perl Term::ReadLine::Stub);
360
+ } elsif (defined $which && defined &{"Term::ReadLine::$which\::readline"}) {
361
+ @ISA = "Term::ReadLine::$which";
362
+ } else {
363
+ @ISA = qw(Term::ReadLine::Stub);
364
+ }
365
+
366
+ package Term::ReadLine::TermCap;
367
+
368
+ # Prompt-start, prompt-end, command-line-start, command-line-end
369
+ # -- zero-width beautifies to emit around prompt and the command line.
370
+ our @rl_term_set = ("","","","");
371
+ # string encoded:
372
+ our $rl_term_set = ',,,';
373
+
374
+ our $terminal;
375
+ sub LoadTermCap {
376
+ return if defined $terminal;
377
+
378
+ require Term::Cap;
379
+ $terminal = Tgetent Term::Cap ({OSPEED => 9600}); # Avoid warning.
380
+ }
381
+
382
+ sub ornaments {
383
+ shift;
384
+ return $rl_term_set unless @_;
385
+ $rl_term_set = shift;
386
+ $rl_term_set ||= ',,,';
387
+ $rl_term_set = 'us,ue,md,me' if $rl_term_set eq '1';
388
+ my @ts = split /,/, $rl_term_set, 4;
389
+ eval { LoadTermCap };
390
+ unless (defined $terminal) {
391
+ warn("Cannot find termcap: $@\n") unless $Term::ReadLine::termcap_nowarn;
392
+ $rl_term_set = ',,,';
393
+ return;
394
+ }
395
+ @rl_term_set = map {$_ ? $terminal->Tputs($_,1) || '' : ''} @ts;
396
+ return $rl_term_set;
397
+ }
398
+
399
+
400
+ package Term::ReadLine::Tk;
401
+
402
+ # This package inserts a Tk->fileevent() before the diamond operator.
403
+ # The Tk watcher dispatches Tk events until the filehandle returned by
404
+ # the$term->IN() accessor becomes ready for reading. It's assumed
405
+ # that the diamond operator will return a line of input immediately at
406
+ # that point.
407
+
408
+ my ($giveup);
409
+
410
+ # maybe in the future the Tk-specific aspects will be removed.
411
+ sub Tk_loop{
412
+ if (ref $Term::ReadLine::toloop)
413
+ {
414
+ $Term::ReadLine::toloop->[0]->($Term::ReadLine::toloop->[2]);
415
+ }
416
+ else
417
+ {
418
+ Tk::DoOneEvent(0) until $giveup;
419
+ $giveup = 0;
420
+ }
421
+ };
422
+
423
+ sub register_Tk {
424
+ my $self = shift;
425
+ unless ($Term::ReadLine::registered++)
426
+ {
427
+ if (ref $Term::ReadLine::toloop)
428
+ {
429
+ $Term::ReadLine::toloop->[2] = $Term::ReadLine::toloop->[1]->($self->IN) if $Term::ReadLine::toloop->[1];
430
+ }
431
+ else
432
+ {
433
+ Tk->fileevent($self->IN,'readable',sub { $giveup = 1});
434
+ }
435
+ }
436
+ };
437
+
438
+ sub tkRunning {
439
+ $Term::ReadLine::toloop = $_[1] if @_ > 1;
440
+ $Term::ReadLine::toloop;
441
+ }
442
+
443
+ sub event_loop {
444
+ shift;
445
+
446
+ # T::RL::Gnu and T::RL::Perl check that this exists, if not,
447
+ # it doesn't call the loop. Those modules will need to be
448
+ # fixed before this can be removed.
449
+ if (not defined &Tk::DoOneEvent)
450
+ {
451
+ *Tk::DoOneEvent = sub {
452
+ die "what?"; # this shouldn't be called.
453
+ }
454
+ }
455
+
456
+ # store the callback in toloop, again so that other modules will
457
+ # recognise it and call us for the loop.
458
+ $Term::ReadLine::toloop = [ @_ ] if @_ > 0; # 0 because we shifted off $self.
459
+ $Term::ReadLine::toloop;
460
+ }
461
+
462
+ sub PERL_UNICODE_STDIN () { 0x0001 }
463
+
464
+ sub get_line {
465
+ my $self = shift;
466
+ my ($in,$out,$str) = @$self;
467
+
468
+ if ($Term::ReadLine::toloop) {
469
+ $self->register_Tk if not $Term::ReadLine::registered;
470
+ $self->Tk_loop;
471
+ }
472
+
473
+ local ($/) = "\n";
474
+ $str = <$in>;
475
+
476
+ utf8::upgrade($str)
477
+ if (${^UNICODE} & PERL_UNICODE_STDIN || defined ${^ENCODING}) &&
478
+ utf8::valid($str);
479
+ print $out $rl_term_set[3];
480
+ # bug in 5.000: chomping empty string creates length -1:
481
+ chomp $str if defined $str;
482
+
483
+ $str;
484
+ }
485
+
486
+ 1;
487
+
git/usr/share/perl5/core_perl/overload/numbers.pm ADDED
@@ -0,0 +1,176 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- mode: Perl; buffer-read-only: t -*-
2
+ #
3
+ # lib/overload/numbers.pm
4
+ #
5
+ # Copyright (C) 2008 by Larry Wall and others
6
+ #
7
+ # You may distribute under the terms of either the GNU General Public
8
+ # License or the Artistic License, as specified in the README file.
9
+ #
10
+ # !!!!!!! DO NOT EDIT THIS FILE !!!!!!!
11
+ # This file is built by regen/overload.pl.
12
+ # Any changes made here will be lost!
13
+
14
+ package overload::numbers;
15
+
16
+ our @names = qw#
17
+ ()
18
+ (${}
19
+ (@{}
20
+ (%{}
21
+ (*{}
22
+ (&{}
23
+ (++
24
+ (--
25
+ (bool
26
+ (0+
27
+ (""
28
+ (!
29
+ (=
30
+ (abs
31
+ (neg
32
+ (<>
33
+ (int
34
+ (<
35
+ (<=
36
+ (>
37
+ (>=
38
+ (==
39
+ (!=
40
+ (lt
41
+ (le
42
+ (gt
43
+ (ge
44
+ (eq
45
+ (ne
46
+ (nomethod
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
+ (cmp
77
+ (~
78
+ (~.
79
+ (atan2
80
+ (cos
81
+ (sin
82
+ (exp
83
+ (log
84
+ (sqrt
85
+ (x
86
+ (x=
87
+ (.
88
+ (.=
89
+ (~~
90
+ (-X
91
+ (qr
92
+ #;
93
+
94
+ our @enums = qw#
95
+ fallback
96
+ to_sv
97
+ to_av
98
+ to_hv
99
+ to_gv
100
+ to_cv
101
+ inc
102
+ dec
103
+ bool_
104
+ numer
105
+ string
106
+ not
107
+ copy
108
+ abs
109
+ neg
110
+ iter
111
+ int
112
+ lt
113
+ le
114
+ gt
115
+ ge
116
+ eq
117
+ ne
118
+ slt
119
+ sle
120
+ sgt
121
+ sge
122
+ seq
123
+ sne
124
+ nomethod
125
+ add
126
+ add_ass
127
+ subtr
128
+ subtr_ass
129
+ mult
130
+ mult_ass
131
+ div
132
+ div_ass
133
+ modulo
134
+ modulo_ass
135
+ pow
136
+ pow_ass
137
+ lshift
138
+ lshift_ass
139
+ rshift
140
+ rshift_ass
141
+ band
142
+ band_ass
143
+ sband
144
+ sband_ass
145
+ bor
146
+ bor_ass
147
+ sbor
148
+ sbor_ass
149
+ bxor
150
+ bxor_ass
151
+ sbxor
152
+ sbxor_ass
153
+ ncmp
154
+ scmp
155
+ compl
156
+ scompl
157
+ atan2
158
+ cos
159
+ sin
160
+ exp
161
+ log
162
+ sqrt
163
+ repeat
164
+ repeat_ass
165
+ concat
166
+ concat_ass
167
+ smart
168
+ ftest
169
+ regexp
170
+ #;
171
+
172
+ { my $i = 0; our %names = map { $_ => $i++ } @names }
173
+
174
+ { my $i = 0; our %enums = map { $_ => $i++ } @enums }
175
+
176
+ # ex: set ro ft=perl:
git/usr/share/perl5/core_perl/source/encoding.pm ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package source::encoding;
2
+
3
+ use v5.40;
4
+
5
+ our $VERSION = '0.01';
6
+
7
+ our $ascii_hint_bits = 0x00000010;
8
+
9
+ sub import {
10
+ unimport(); # Get rid of any 'use utf8'
11
+ my (undef, $arg) = @_;
12
+ if ($arg eq 'utf8') {
13
+ require utf8;
14
+ utf8->import;
15
+ return;
16
+ }
17
+ elsif ($arg eq 'ascii') {
18
+ $^H |= $ascii_hint_bits;
19
+ return;
20
+ }
21
+
22
+ die "Bad argument for source::encoding: '$arg'";
23
+ }
24
+
25
+ sub unimport {
26
+ $^H &= ~$ascii_hint_bits;
27
+ utf8->unimport;
28
+ }
29
+
30
+ 1;
31
+ __END__
32
+
33
+ =head1 NAME
34
+
35
+ source::encoding -- Declare Perl source code encoding
36
+
37
+ =head1 SYNOPSIS
38
+
39
+ use source::encoding 'ascii';
40
+ use source::encoding 'utf8';
41
+ no source::encoding;
42
+
43
+ =head1 DESCRIPTION
44
+
45
+ These days, Perl code either generally contains only ASCII characters with
46
+ C<\x{}> and similar escapes to represent non-ASCII, or C<S<use utf8>> is used
47
+ to indicate that the source code itself contains characters encoded as UTF-8.
48
+
49
+ That means that a character in the source code not meeting these criteria is
50
+ often a typographical error. This pragma is used to tell Perl to raise an
51
+ error when this happens.
52
+
53
+ S<C<use source::encoding 'utf8'>> is a synonym for S<C<use utf8>>. They may
54
+ be used interchangeably.
55
+
56
+ S<C<use source::encoding 'ascii'>> turns off any UTF-8 expectations, and
57
+ raises a fatal error if any character within its scope in the input source
58
+ code is not ASCII (or ASCII-equivalent on EBCDIC systems).
59
+
60
+ S<C<no source::encoding>> turns off any UTF-8/ASCII expectations for the
61
+ remainder of its scope. The meaning of non-ASCII characters is then
62
+ undefined.
63
+
64
+ S<C<use source::encoding 'ascii'>> is automatically enabled within the
65
+ lexical scope of a S<C<use v5.41.0>> or higher.
66
+
67
+ =head1 SEE ALSO
68
+
69
+ L<utf8>
70
+
71
+ =cut