Update -getUploadSafeName: to not fail with certain characters
[printdrop.git] / Source / AppController.m
1 /*
2 * PrintDrop
3 * Copyright (c) 2008, Blue Static <http://www.bluestatic.org>
4 *
5 * This program is free software; you can redistribute it and/or modify it under the terms of the GNU
6 * General Public License as published by the Free Software Foundation; either version 2 of the
7 * License, or (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
10 * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 * General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License along with this program; if not,
14 * write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
15 */
16
17 #import "AppController.h"
18 #import <libssh2.h>
19 #import <sys/socket.h>
20 #import <arpa/inet.h>
21 #include <netdb.h>
22 #include <stdlib.h>
23 #include <WebKit/WebKit.h>
24 #include <unistd.h>
25
26 @interface AppController (Private)
27 - (void)setStatus:(NSString *)msg isError:(BOOL)error;
28
29 - (void)readChannel:(LIBSSH2_CHANNEL *)channel;
30 - (void)uploadAndPrint:(id)sender;
31
32 - (NSString *)getUploadSafeName:(NSString *)name;
33 @end
34
35
36 @implementation AppController
37
38 /**
39 * Set up the printer list
40 */
41 - (id)init
42 {
43 if (self = [super init])
44 {
45 printers = [[NSArray alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Printers" ofType:@"plist"]];
46 }
47 return self;
48 }
49
50 /**
51 * Dealloc
52 */
53 - (void)dealloc
54 {
55 [printers release];
56 [super dealloc];
57 }
58
59 /**
60 * Sets the status text
61 */
62 - (void)setStatus:(NSString *)msg isError:(BOOL)error
63 {
64 [status setStringValue:msg];
65 if (error)
66 {
67 [status setTextColor:[NSColor redColor]];
68 [progress stopAnimation:self];
69 }
70 else
71 {
72 [status setTextColor:[NSColor blackColor]];
73 }
74 }
75
76 /**
77 * Awake from NIB
78 */
79 - (void)awakeFromNib
80 {
81 [helpWindow center];
82 NSString *helpPath = [[NSBundle mainBundle] pathForResource:@"Help" ofType:@"html"];
83 [[helpWebView mainFrame] loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:helpPath]]];
84
85 [window makeKeyAndOrderFront:self];
86
87 NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
88 NSString *hash = [[[NSBundle mainBundle] infoDictionary] valueForKey:@"CFBundleVersion"];
89 if (![[defaults valueForKey:@"LastVersionHelpWindow"] isEqualToString:hash])
90 {
91 [helpWindow makeKeyAndOrderFront:self];
92 [defaults setObject:hash forKey:@"LastVersionHelpWindow"];
93 }
94 }
95
96 /**
97 * Reads through a channel (in non-blocking) mode until there is no more left to read
98 * and then it returns. This calls sleep(1) so that the channel can have time to process.
99 * Be sure this is threaded otherwis the interface will stall.
100 */
101 - (void)readChannel:(LIBSSH2_CHANNEL *)channel
102 {
103 libssh2_channel_set_blocking(channel, 0);
104
105 char buf[1024];
106 int numbytes;
107 do
108 {
109 memset(&buf, '\0', sizeof(buf));
110 numbytes = libssh2_channel_read(channel, buf, sizeof(buf));
111 sleep(1);
112 NSLog(@"SSH buffer: %s", buf);
113 } while (libssh2_poll_channel_read(channel, 0));
114 }
115
116 /**
117 * Sends an item to the printer
118 */
119 - (IBAction)print:(id)sender
120 {
121 [NSThread detachNewThreadSelector:@selector(uploadAndPrint:) toTarget:self withObject:sender];
122 }
123
124 /**
125 * Opens an SSH session, creates a SCP channel to upload the file, followed by a shell channel
126 * to queue up LPR
127 */
128 - (void)uploadAndPrint:(id)sender
129 {
130 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
131
132 [progress startAnimation:self];
133 [progress setHidden:NO];
134 [status setHidden:NO];
135 [goButton setEnabled:NO];
136
137 FILE *localFile;
138 struct stat fileInfo;
139 const char *fileName = [[self getUploadSafeName:[dragRegion filePath]] UTF8String];
140
141 [self setStatus:@"Connecting to acs.bu.edu" isError:NO];
142 struct sockaddr_in sin;
143 int sock = socket(AF_INET, SOCK_STREAM, 0);
144 sin.sin_port = htons(22);
145 sin.sin_family = AF_INET;
146
147 struct hostent *host = gethostbyname("acs.bu.edu");
148 memcpy(&sin.sin_addr, host->h_addr_list[0], host->h_length);
149
150 if (stat([[dragRegion filePath] UTF8String], &fileInfo))
151 {
152 return [self setStatus:@"Invalid file selected" isError:YES];
153 }
154
155 if (connect(sock, (struct sockaddr *)(&sin), sizeof(struct sockaddr_in)) != 0)
156 {
157 return [self setStatus:@"Could not connect to acs.bu.edu" isError:YES];
158 }
159
160 LIBSSH2_SESSION *ssh = libssh2_session_init();
161 if (ssh == NULL)
162 {
163 return [self setStatus:@"Failed to initialize SSH context" isError:YES];
164 }
165
166 if (libssh2_session_startup(ssh, sock))
167 {
168 return [self setStatus:@"Could not tunnel over SSH" isError:YES];
169 }
170
171 if (libssh2_userauth_password(ssh, [[username stringValue] UTF8String], [[password stringValue] UTF8String]))
172 {
173 [self setStatus:@"Bad username/password" isError:YES];
174 goto shutdown;
175 }
176
177 LIBSSH2_CHANNEL *channel = libssh2_scp_send(ssh, fileName, 0755, (unsigned long)fileInfo.st_size);
178 if (!channel)
179 {
180 [self setStatus:@"Unable to open upload SCP session" isError:YES];
181 goto shutdown;
182 }
183
184 [self setStatus:@"Uploading file..." isError:NO];
185
186 localFile = fopen([[dragRegion filePath] UTF8String], "r");
187 char buf[1024];
188 char *pbuf;
189 int numread, numwrote;
190 do
191 {
192 numread = fread(buf, 1, sizeof(buf), localFile);
193 if (numread <= 0)
194 {
195 break;
196 }
197
198 pbuf = buf;
199 do
200 {
201 numwrote = libssh2_channel_write(channel, pbuf, numread);
202 pbuf += numwrote;
203 numread -= numread;
204 } while (numwrote > 0);
205
206 } while(1);
207
208 [self setStatus:@"File uploaded!" isError:NO];
209
210 libssh2_channel_send_eof(channel);
211 libssh2_channel_wait_eof(channel);
212 libssh2_channel_wait_closed(channel);
213 libssh2_channel_free(channel);
214 channel = NULL;
215
216 channel = libssh2_channel_open_session(ssh);
217 if (!channel)
218 {
219 [self setStatus:@"Could not open SSH channel for printing" isError:YES];
220 goto shutdown;
221 }
222
223 if (libssh2_channel_request_pty(channel, "vanilla"))
224 {
225 [self setStatus:@"Could not open ANSI TTY" isError:YES];
226 goto shutdown;
227 }
228
229 if (libssh2_channel_shell(channel))
230 {
231 [self setStatus:@"Failed to open remote shell" isError:YES];
232 goto shutdown;
233 }
234
235 [self setStatus:@"Opened remote SSH shell" isError:NO];
236
237 // read the banner
238 [self readChannel:channel];
239
240 // ACS outage messages --> skip some more
241 char *delay = "q\r\n\0";
242 libssh2_channel_write(channel, delay, sizeof(char) * strlen(delay));
243 [self readChannel:channel];
244
245 // send the job to lpr
246 char *cmd;
247 #ifndef BLU_DEBUG
248 NSString *printer = [[printersController selection] valueForKey:@"unixName"];
249 cmd = (char *)[[NSString stringWithFormat:@"lpr -m -#%d -P%@ %s\r\n\0", [[copiesButtons selectedCell] tag], printer, fileName] UTF8String];
250 #else
251 NSLog(@"tag = %@ [%d]", [copiesButtons selectedCell], [[copiesButtons selectedCell] tag]);
252 if ([[copiesButtons selectedCell] tag] == 1)
253 cmd = "touch __PRINT_1__\r\n\0";
254 else
255 cmd = "touch __PRINT_2__\r\n\0";
256 #endif
257 libssh2_channel_write(channel, cmd, sizeof(char) * strlen(cmd));
258 [self readChannel:channel];
259
260 // remove our temp file
261 cmd = (char *)[[NSString stringWithFormat:@"rm -f %s\r\n\0", fileName] UTF8String];
262 libssh2_channel_write(channel, cmd, sizeof(char) * strlen(cmd));
263 [self readChannel:channel];
264
265 [self setStatus:@"Printed!" isError:NO];
266
267 libssh2_channel_send_eof(channel);
268 libssh2_channel_eof(channel);
269 libssh2_channel_close(channel);
270
271 shutdown:
272 if (channel)
273 {
274 //libssh2_channel_free(channel);
275 channel = NULL;
276 }
277 libssh2_session_disconnect(ssh, "Normal disconnect.");
278 libssh2_session_free(ssh);
279
280 close(sock);
281
282 [dragRegion clearFile];
283 [progress stopAnimation:self];
284
285 [pool release];
286 }
287
288 /**
289 * Returns an NSString that is safe for uploding onto the server
290 */
291 - (NSString *)getUploadSafeName:(NSString *)name
292 {
293 NSMutableString *safeName = [NSMutableString string];
294
295 name = [name lastPathComponent];
296 name = [name stringByDeletingPathExtension];
297
298 for (int i = 0, j = 0; i < [name length] && j < 20; i++)
299 {
300 char c = [name characterAtIndex:i];
301 if ((c >= 48 && c <= 57) || (c >= 65 && c <= 90) || (c >= 97 && 122) || c == 95)
302 {
303 [safeName appendFormat:@"%c", c];
304 j++;
305 }
306 else if (c == 32)
307 {
308 if (j > 0 && [safeName characterAtIndex:j - 1] != '-')
309 {
310 [safeName appendString:@"_"];
311 j++;
312 }
313 }
314 else if (c >= 38 && c <= 46)
315 {
316 if (j > 0 && [safeName characterAtIndex:j - 1] != '_')
317 {
318 [safeName appendString:@"-"];
319 j++;
320 }
321 }
322 }
323
324 srandomdev();
325 return [NSString stringWithFormat:@"~/%@.%d.pdf", safeName, random()];
326 }
327
328 @end