View Javadoc
1   /*
2    * Copyright (C) 2014, Alexey Kuznetsov <axet@me.com>
3    *
4    * This program and the accompanying materials are made available
5    * under the terms of the Eclipse Distribution License v1.0 which
6    * accompanies this distribution, is reproduced below, and is
7    * available at http://www.eclipse.org/org/documents/edl-v10.php
8    *
9    * All rights reserved.
10   *
11   * Redistribution and use in source and binary forms, with or
12   * without modification, are permitted provided that the following
13   * conditions are met:
14   *
15   * - Redistributions of source code must retain the above copyright
16   *   notice, this list of conditions and the following disclaimer.
17   *
18   * - Redistributions in binary form must reproduce the above
19   *   copyright notice, this list of conditions and the following
20   *   disclaimer in the documentation and/or other materials provided
21   *   with the distribution.
22   *
23   * - Neither the name of the Eclipse Foundation, Inc. nor the
24   *   names of its contributors may be used to endorse or promote
25   *   products derived from this software without specific prior
26   *   written permission.
27   *
28   * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
29   * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
30   * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
31   * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
32   * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
33   * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
34   * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
35   * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
36   * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
37   * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
38   * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
39   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
40   * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
41   */
42  
43  package org.eclipse.jgit.transport;
44  
45  import static java.nio.charset.StandardCharsets.UTF_8;
46  
47  import java.io.BufferedReader;
48  import java.io.File;
49  import java.io.FileInputStream;
50  import java.io.IOException;
51  import java.io.InputStreamReader;
52  import java.time.Instant;
53  import java.util.Collection;
54  import java.util.HashMap;
55  import java.util.Locale;
56  import java.util.Map;
57  import java.util.TreeMap;
58  import java.util.regex.Matcher;
59  import java.util.regex.Pattern;
60  
61  import org.eclipse.jgit.util.FS;
62  
63  /**
64   * NetRC file parser.
65   *
66   * @since 3.5
67   */
68  public class NetRC {
69  	static final Pattern NETRC = Pattern.compile("(\\S+)"); //$NON-NLS-1$
70  
71  	/**
72  	 * 'default' netrc entry. This is the same as machine name except that
73  	 * default matches any name. There can be only one default token, and it
74  	 * must be after all machine tokens.
75  	 */
76  	static final String DEFAULT_ENTRY = "default"; //$NON-NLS-1$
77  
78  	/**
79  	 * .netrc file entry
80  	 */
81  	public static class NetRCEntry {
82  		/**
83  		 * login netrc entry
84  		 */
85  		public String login;
86  
87  		/**
88  		 * password netrc entry
89  		 */
90  		public char[] password;
91  
92  		/**
93  		 * machine netrc entry
94  		 */
95  		public String machine;
96  
97  		/**
98  		 * account netrc entry
99  		 */
100 		public String account;
101 
102 		/**
103 		 * macdef netrc entry. Defines a macro. This token functions like the
104 		 * ftp macdef command functions. A macro is defined with the specified
105 		 * name; its contents begins with the next .netrc line and continues
106 		 * until a null line (consecutive new-line characters) is encountered.
107 		 * If a macro named init is defined, it is automatically executed as the
108 		 * last step in the auto-login process.
109 		 */
110 		public String macdef;
111 
112 		/**
113 		 * macro script body of macdef entry.
114 		 */
115 		public String macbody;
116 
117 		/**
118 		 * Default constructor
119 		 */
120 		public NetRCEntry() {
121 		}
122 
123 		boolean complete() {
124 			return login != null && password != null && machine != null;
125 		}
126 	}
127 
128 	private File netrc;
129 
130 	private Instant lastModified;
131 
132 	private Map<String, NetRCEntry> hosts = new HashMap<>();
133 
134 	private static final TreeMap<String, State> STATE = new TreeMap<>() {
135 		private static final long serialVersionUID = -4285910831814853334L;
136 		{
137 			put("machine", State.MACHINE); //$NON-NLS-1$
138 			put("login", State.LOGIN); //$NON-NLS-1$
139 			put("password", State.PASSWORD); //$NON-NLS-1$
140 			put(DEFAULT_ENTRY, State.DEFAULT);
141 			put("account", State.ACCOUNT); //$NON-NLS-1$
142 			put("macdef", State.MACDEF); //$NON-NLS-1$
143 		}
144 	};
145 
146 	enum State {
147 		COMMAND, MACHINE, LOGIN, PASSWORD, DEFAULT, ACCOUNT, MACDEF
148 	}
149 
150 	/**
151 	 * <p>Constructor for NetRC.</p>
152 	 */
153 	public NetRC() {
154 		netrc = getDefaultFile();
155 		if (netrc != null)
156 			parse();
157 	}
158 
159 	/**
160 	 * <p>Constructor for NetRC.</p>
161 	 *
162 	 * @param netrc
163 	 *            the .netrc file
164 	 */
165 	public NetRC(File netrc) {
166 		this.netrc = netrc;
167 		parse();
168 	}
169 
170 	private static File getDefaultFile() {
171 		File home = FS.DETECTED.userHome();
172 		File netrc = new File(home, ".netrc"); //$NON-NLS-1$
173 		if (netrc.exists())
174 			return netrc;
175 
176 		netrc = new File(home, "_netrc"); //$NON-NLS-1$
177 		if (netrc.exists())
178 			return netrc;
179 
180 		return null;
181 	}
182 
183 	/**
184 	 * Get entry by host name
185 	 *
186 	 * @param host
187 	 *            the host name
188 	 * @return entry associated with host name or null
189 	 */
190 	public NetRCEntry getEntry(String host) {
191 		if (netrc == null)
192 			return null;
193 
194 		if (!this.lastModified
195 				.equals(FS.DETECTED.lastModifiedInstant(this.netrc))) {
196 			parse();
197 		}
198 
199 		NetRCEntry entry = this.hosts.get(host);
200 
201 		if (entry == null)
202 			entry = this.hosts.get(DEFAULT_ENTRY);
203 
204 		return entry;
205 	}
206 
207 	/**
208 	 * Get all entries collected from .netrc file
209 	 *
210 	 * @return all entries collected from .netrc file
211 	 */
212 	public Collection<NetRCEntry> getEntries() {
213 		return hosts.values();
214 	}
215 
216 	private void parse() {
217 		this.hosts.clear();
218 		this.lastModified = FS.DETECTED.lastModifiedInstant(this.netrc);
219 
220 		try (BufferedReader r = new BufferedReader(
221 				new InputStreamReader(new FileInputStream(netrc), UTF_8))) {
222 			String line = null;
223 
224 			NetRCEntry entry = new NetRCEntry();
225 
226 			State state = State.COMMAND;
227 
228 			String macbody = ""; //$NON-NLS-1$
229 
230 			Matcher matcher = NETRC.matcher(""); //$NON-NLS-1$
231 			while ((line = r.readLine()) != null) {
232 
233 				// reading macbody
234 				if (entry.macdef != null && entry.macbody == null) {
235 					if (line.length() == 0) {
236 						entry.macbody = macbody;
237 						macbody = ""; //$NON-NLS-1$
238 						continue;
239 					}
240 					macbody += line + "\n"; //$NON-NLS-1$;
241 					continue;
242 				}
243 
244 				matcher.reset(line);
245 				while (matcher.find()) {
246 					String command = matcher.group().toLowerCase(Locale.ROOT);
247 					if (command.startsWith("#")) { //$NON-NLS-1$
248 						matcher.reset(""); //$NON-NLS-1$
249 						continue;
250 					}
251 					state = STATE.get(command);
252 					if (state == null)
253 						state = State.COMMAND;
254 
255 					switch (state) {
256 					case COMMAND:
257 						break;
258 					case ACCOUNT:
259 						if (entry.account != null && entry.complete()) {
260 							hosts.put(entry.machine, entry);
261 							entry = new NetRCEntry();
262 						}
263 						if (matcher.find())
264 							entry.account = matcher.group();
265 						state = State.COMMAND;
266 						break;
267 					case LOGIN:
268 						if (entry.login != null && entry.complete()) {
269 							hosts.put(entry.machine, entry);
270 							entry = new NetRCEntry();
271 						}
272 						if (matcher.find())
273 							entry.login = matcher.group();
274 						state = State.COMMAND;
275 						break;
276 					case PASSWORD:
277 						if (entry.password != null && entry.complete()) {
278 							hosts.put(entry.machine, entry);
279 							entry = new NetRCEntry();
280 						}
281 						if (matcher.find())
282 							entry.password = matcher.group().toCharArray();
283 						state = State.COMMAND;
284 						break;
285 					case DEFAULT:
286 						if (entry.machine != null && entry.complete()) {
287 							hosts.put(entry.machine, entry);
288 							entry = new NetRCEntry();
289 						}
290 						entry.machine = DEFAULT_ENTRY;
291 						state = State.COMMAND;
292 						break;
293 					case MACDEF:
294 						if (entry.macdef != null && entry.complete()) {
295 							hosts.put(entry.machine, entry);
296 							entry = new NetRCEntry();
297 						}
298 						if (matcher.find())
299 							entry.macdef = matcher.group();
300 						state = State.COMMAND;
301 						break;
302 					case MACHINE:
303 						if (entry.machine != null && entry.complete()) {
304 							hosts.put(entry.machine, entry);
305 							entry = new NetRCEntry();
306 						}
307 						if (matcher.find())
308 							entry.machine = matcher.group();
309 						state = State.COMMAND;
310 						break;
311 					}
312 				}
313 			}
314 
315 			// reading macbody on EOF
316 			if (entry.macdef != null && entry.macbody == null)
317 				entry.macbody = macbody;
318 
319 			if (entry.complete())
320 				hosts.put(entry.machine, entry);
321 		} catch (IOException e) {
322 			throw new RuntimeException(e);
323 		}
324 	}
325 }