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 java.io.BufferedReader;
46  import java.io.File;
47  import java.io.FileReader;
48  import java.io.IOException;
49  import java.time.Instant;
50  import java.util.Collection;
51  import java.util.HashMap;
52  import java.util.Locale;
53  import java.util.Map;
54  import java.util.TreeMap;
55  import java.util.regex.Matcher;
56  import java.util.regex.Pattern;
57  
58  import org.eclipse.jgit.util.FS;
59  
60  /**
61   * NetRC file parser.
62   *
63   * @since 3.5
64   */
65  public class NetRC {
66  	static final Pattern NETRC = Pattern.compile("(\\S+)"); //$NON-NLS-1$
67  
68  	/**
69  	 * 'default' netrc entry. This is the same as machine name except that
70  	 * default matches any name. There can be only one default token, and it
71  	 * must be after all machine tokens.
72  	 */
73  	static final String DEFAULT_ENTRY = "default"; //$NON-NLS-1$
74  
75  	/**
76  	 * .netrc file entry
77  	 */
78  	public static class NetRCEntry {
79  		/**
80  		 * login netrc entry
81  		 */
82  		public String login;
83  
84  		/**
85  		 * password netrc entry
86  		 */
87  		public char[] password;
88  
89  		/**
90  		 * machine netrc entry
91  		 */
92  		public String machine;
93  
94  		/**
95  		 * account netrc entry
96  		 */
97  		public String account;
98  
99  		/**
100 		 * macdef netrc entry. Defines a macro. This token functions like the
101 		 * ftp macdef command functions. A macro is defined with the specified
102 		 * name; its contents begins with the next .netrc line and continues
103 		 * until a null line (consecutive new-line characters) is encountered.
104 		 * If a macro named init is defined, it is automatically executed as the
105 		 * last step in the auto-login process.
106 		 */
107 		public String macdef;
108 
109 		/**
110 		 * macro script body of macdef entry.
111 		 */
112 		public String macbody;
113 
114 		/**
115 		 * Default constructor
116 		 */
117 		public NetRCEntry() {
118 		}
119 
120 		boolean complete() {
121 			return login != null && password != null && machine != null;
122 		}
123 	}
124 
125 	private File netrc;
126 
127 	private Instant lastModified;
128 
129 	private Map<String, NetRCEntry> hosts = new HashMap<>();
130 
131 	private static final TreeMap<String, State> STATE = new TreeMap<String, NetRC.State>() {
132 		private static final long serialVersionUID = -4285910831814853334L;
133 		{
134 			put("machine", State.MACHINE); //$NON-NLS-1$
135 			put("login", State.LOGIN); //$NON-NLS-1$
136 			put("password", State.PASSWORD); //$NON-NLS-1$
137 			put(DEFAULT_ENTRY, State.DEFAULT);
138 			put("account", State.ACCOUNT); //$NON-NLS-1$
139 			put("macdef", State.MACDEF); //$NON-NLS-1$
140 		}
141 	};
142 
143 	enum State {
144 		COMMAND, MACHINE, LOGIN, PASSWORD, DEFAULT, ACCOUNT, MACDEF
145 	}
146 
147 	/**
148 	 * <p>Constructor for NetRC.</p>
149 	 */
150 	public NetRC() {
151 		netrc = getDefaultFile();
152 		if (netrc != null)
153 			parse();
154 	}
155 
156 	/**
157 	 * <p>Constructor for NetRC.</p>
158 	 *
159 	 * @param netrc
160 	 *            the .netrc file
161 	 */
162 	public NetRC(File netrc) {
163 		this.netrc = netrc;
164 		parse();
165 	}
166 
167 	private static File getDefaultFile() {
168 		File home = FS.DETECTED.userHome();
169 		File netrc = new File(home, ".netrc"); //$NON-NLS-1$
170 		if (netrc.exists())
171 			return netrc;
172 
173 		netrc = new File(home, "_netrc"); //$NON-NLS-1$
174 		if (netrc.exists())
175 			return netrc;
176 
177 		return null;
178 	}
179 
180 	/**
181 	 * Get entry by host name
182 	 *
183 	 * @param host
184 	 *            the host name
185 	 * @return entry associated with host name or null
186 	 */
187 	public NetRCEntry getEntry(String host) {
188 		if (netrc == null)
189 			return null;
190 
191 		if (!this.lastModified
192 				.equals(FS.DETECTED.lastModifiedInstant(this.netrc))) {
193 			parse();
194 		}
195 
196 		NetRCEntry entry = this.hosts.get(host);
197 
198 		if (entry == null)
199 			entry = this.hosts.get(DEFAULT_ENTRY);
200 
201 		return entry;
202 	}
203 
204 	/**
205 	 * Get all entries collected from .netrc file
206 	 *
207 	 * @return all entries collected from .netrc file
208 	 */
209 	public Collection<NetRCEntry> getEntries() {
210 		return hosts.values();
211 	}
212 
213 	private void parse() {
214 		this.hosts.clear();
215 		this.lastModified = FS.DETECTED.lastModifiedInstant(this.netrc);
216 
217 		try (BufferedReader r = new BufferedReader(new FileReader(netrc))) {
218 			String line = null;
219 
220 			NetRCEntry entry = new NetRCEntry();
221 
222 			State state = State.COMMAND;
223 
224 			String macbody = ""; //$NON-NLS-1$
225 
226 			Matcher matcher = NETRC.matcher(""); //$NON-NLS-1$
227 			while ((line = r.readLine()) != null) {
228 
229 				// reading macbody
230 				if (entry.macdef != null && entry.macbody == null) {
231 					if (line.length() == 0) {
232 						entry.macbody = macbody;
233 						macbody = ""; //$NON-NLS-1$
234 						continue;
235 					}
236 					macbody += line + "\n"; //$NON-NLS-1$;
237 					continue;
238 				}
239 
240 				matcher.reset(line);
241 				while (matcher.find()) {
242 					String command = matcher.group().toLowerCase(Locale.ROOT);
243 					if (command.startsWith("#")) { //$NON-NLS-1$
244 						matcher.reset(""); //$NON-NLS-1$
245 						continue;
246 					}
247 					state = STATE.get(command);
248 					if (state == null)
249 						state = State.COMMAND;
250 
251 					switch (state) {
252 					case COMMAND:
253 						break;
254 					case ACCOUNT:
255 						if (entry.account != null && entry.complete()) {
256 							hosts.put(entry.machine, entry);
257 							entry = new NetRCEntry();
258 						}
259 						if (matcher.find())
260 							entry.account = matcher.group();
261 						state = State.COMMAND;
262 						break;
263 					case LOGIN:
264 						if (entry.login != null && entry.complete()) {
265 							hosts.put(entry.machine, entry);
266 							entry = new NetRCEntry();
267 						}
268 						if (matcher.find())
269 							entry.login = matcher.group();
270 						state = State.COMMAND;
271 						break;
272 					case PASSWORD:
273 						if (entry.password != null && entry.complete()) {
274 							hosts.put(entry.machine, entry);
275 							entry = new NetRCEntry();
276 						}
277 						if (matcher.find())
278 							entry.password = matcher.group().toCharArray();
279 						state = State.COMMAND;
280 						break;
281 					case DEFAULT:
282 						if (entry.machine != null && entry.complete()) {
283 							hosts.put(entry.machine, entry);
284 							entry = new NetRCEntry();
285 						}
286 						entry.machine = DEFAULT_ENTRY;
287 						state = State.COMMAND;
288 						break;
289 					case MACDEF:
290 						if (entry.macdef != null && entry.complete()) {
291 							hosts.put(entry.machine, entry);
292 							entry = new NetRCEntry();
293 						}
294 						if (matcher.find())
295 							entry.macdef = matcher.group();
296 						state = State.COMMAND;
297 						break;
298 					case MACHINE:
299 						if (entry.machine != null && entry.complete()) {
300 							hosts.put(entry.machine, entry);
301 							entry = new NetRCEntry();
302 						}
303 						if (matcher.find())
304 							entry.machine = matcher.group();
305 						state = State.COMMAND;
306 						break;
307 					}
308 				}
309 			}
310 
311 			// reading macbody on EOF
312 			if (entry.macdef != null && entry.macbody == null)
313 				entry.macbody = macbody;
314 
315 			if (entry.complete())
316 				hosts.put(entry.machine, entry);
317 		} catch (IOException e) {
318 			throw new RuntimeException(e);
319 		}
320 	}
321 }