fixed handling of 139/445 in clients
[samba.git] / source / client / smbspool.c
1 /* 
2    Unix SMB/Netbios implementation.
3    Version 2.0.
4    SMB backend for the Common UNIX Printing System ("CUPS")
5    Copyright 1999 by Easy Software Products
6    Copyright Andrew Tridgell 1994-1998
7    
8    This program is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 2 of the License, or
11    (at your option) any later version.
12    
13    This program is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17    
18    You should have received a copy of the GNU General Public License
19    along with this program; if not, write to the Free Software
20    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
21 */
22
23 #define NO_SYSLOG
24
25 #include "includes.h"
26
27 /*
28  * Globals...
29  */
30
31 extern BOOL             in_client;      /* Boolean for client library */
32 extern struct in_addr   ipzero;         /* Any address */
33
34
35 /*
36  * Local functions...
37  */
38
39 static void             list_devices(void);
40 static struct cli_state *smb_connect(char *, char *, char *, char *, char *);
41 static int              smb_print(struct cli_state *, char *, FILE *);
42
43
44 /*
45  * 'main()' - Main entry for SMB backend.
46  */
47
48  int                            /* O - Exit status */
49  main(int  argc,                        /* I - Number of command-line arguments */
50      char *argv[])              /* I - Command-line arguments */
51 {
52   int           i;              /* Looping var */
53   int           copies;         /* Number of copies */
54   char          uri[1024],      /* URI */
55                 *sep,           /* Pointer to separator */
56                 *username,      /* Username */
57                 *password,      /* Password */
58                 *workgroup,     /* Workgroup */
59                 *server,        /* Server name */
60                 *printer;       /* Printer name */
61   FILE          *fp;            /* File to print */
62   int           status=0;               /* Status of LPD job */
63   struct cli_state *cli;        /* SMB interface */
64
65   /* we expect the URI in argv[0]. Detect the case where it is in argv[1] and cope */
66   if (argc > 2 && strncmp(argv[0],"smb://", 6) && !strncmp(argv[1],"smb://", 6)) {
67           argv++;
68           argc--;
69   }
70
71   if (argc == 1)
72   {
73    /*
74     * NEW!  In CUPS 1.1 the backends are run with no arguments to list the
75     *       available devices.  These can be devices served by this backend
76     *       or any other backends (i.e. you can have an SNMP backend that
77     *       is only used to enumerate the available network printers... :)
78     */
79
80     list_devices();
81     return (0);
82   }
83
84   if (argc < 6 || argc > 7)
85   {
86     fprintf(stderr, "Usage: %s [DEVICE_URI] job-id user title copies options [file]\n",
87             argv[0]);
88     fputs("       The DEVICE_URI environment variable can also contain the\n", stderr);
89     fputs("       destination printer:\n", stderr);
90     fputs("\n", stderr);
91     fputs("           smb://[username:password@][workgroup/]server/printer\n", stderr);
92     return (1);
93   }
94
95  /*
96   * If we have 7 arguments, print the file named on the command-line.
97   * Otherwise, print data from stdin...
98   */
99
100   if (argc == 6)
101   {
102    /*
103     * Print from Copy stdin to a temporary file...
104     */
105
106     fp     = stdin;
107     copies = 1;
108   }
109   else if ((fp = fopen(argv[6], "rb")) == NULL)
110   {
111     perror("ERROR: Unable to open print file");
112     return (1);
113   }
114   else
115     copies = atoi(argv[4]);
116
117  /*
118   * Find the URI...
119   */
120
121   if (strncmp(argv[0], "smb://", 6) == 0)
122     strncpy(uri, argv[0], sizeof(uri) - 1);
123   else if (getenv("DEVICE_URI") != NULL)
124     strncpy(uri, getenv("DEVICE_URI"), sizeof(uri) - 1);
125   else
126   {
127     fputs("ERROR: No device URI found in argv[0] or DEVICE_URI environment variable!\n", stderr);
128     return (1);
129   }
130
131   uri[sizeof(uri) - 1] = '\0';
132
133  /*
134   * Extract the destination from the URI...
135   */
136
137   if ((sep = strrchr_m(uri, '@')) != NULL)
138   {
139     username = uri + 6;
140     *sep++ = '\0';
141
142     server = sep;
143
144    /*
145     * Extract password as needed...
146     */
147
148     if ((password = strchr_m(username, ':')) != NULL)
149       *password++ = '\0';
150     else
151       password = "";
152   }
153   else
154   {
155     username = "";
156     password = "";
157     server   = uri + 6;
158   }
159
160   if ((sep = strchr_m(server, '/')) == NULL)
161   {
162     fputs("ERROR: Bad URI - need printer name!\n", stderr);
163     return (1);
164   }
165
166   *sep++ = '\0';
167   printer = sep;
168
169   if ((sep = strchr_m(printer, '/')) != NULL)
170   {
171    /*
172     * Convert to smb://[username:password@]workgroup/server/printer...
173     */
174
175     *sep++ = '\0';
176
177     workgroup = server;
178     server    = printer;
179     printer   = sep;
180   }
181   else
182     workgroup = NULL;
183
184  /*
185   * Setup the SAMBA server state...
186   */
187
188   setup_logging("smbspool", True);
189
190   TimeInit();
191
192   in_client = True;   /* Make sure that we tell lp_load we are */
193
194   if (!lp_load(CONFIGFILE, True, False, False))
195   {
196     fprintf(stderr, "ERROR: Can't load %s - run testparm to debug it\n", CONFIGFILE);
197     return (1);
198   }
199
200   if (workgroup == NULL)
201     workgroup = lp_workgroup();
202
203   load_interfaces();
204
205   do
206   {
207     if ((cli = smb_connect(workgroup, server, printer, username, password)) == NULL)
208     {
209       if (getenv("CLASS") == NULL)
210       {
211         perror("ERROR: Unable to connect to SAMBA host, will retry in 60 seconds...");
212         sleep (60);
213       }
214       else
215       {
216         perror("ERROR: Unable to connect to SAMBA host, trying next printer...");
217         return (1);
218       }
219     }
220   }
221   while (cli == NULL);
222
223  /*
224   * Now that we are connected to the server, ignore SIGTERM so that we
225   * can finish out any page data the driver sends (e.g. to eject the
226   * current page...  Only ignore SIGTERM if we are printing data from
227   * stdin (otherwise you can't cancel raw jobs...)
228   */
229
230   if (argc < 7)
231     CatchSignal(SIGTERM, SIG_IGN);
232
233  /*
234   * Queue the job...
235   */
236
237   for (i = 0; i < copies; i ++)
238     if ((status = smb_print(cli, argv[3] /* title */, fp)) != 0)
239       break;
240
241   cli_shutdown(cli);
242
243  /*
244   * Return the queue status...
245   */
246
247   return (status);
248 }
249
250
251 /*
252  * 'list_devices()' - List the available printers seen on the network...
253  */
254
255 static void
256 list_devices(void)
257 {
258  /*
259   * Eventually, search the local workgroup for available hosts and printers.
260   */
261
262   puts("network smb \"Unknown\" \"Windows Printer via SAMBA\"");
263 }
264
265
266 /*
267  * 'smb_connect()' - Return a connection to a server.
268  */
269
270 static struct cli_state *               /* O - SMB connection */
271 smb_connect(char *workgroup,            /* I - Workgroup */
272             char *server,               /* I - Server */
273             char *share,                /* I - Printer */
274             char *username,             /* I - Username */
275             char *password)             /* I - Password */
276 {
277   struct cli_state      *c;             /* New connection */
278   struct nmb_name       called,         /* NMB name of server */
279                         calling;        /* NMB name of client */
280   struct in_addr        ip;             /* IP address of server */
281   pstring               myname;         /* Client name */
282
283
284  /*
285   * Get the names and addresses of the client and server...
286   */
287
288   get_myname(myname);  
289
290   ip = ipzero;
291
292   make_nmb_name(&calling, myname, 0x0);
293   make_nmb_name(&called, server, 0x20);
294
295  /*
296   * Open a new connection to the SMB server...
297   */
298
299   if ((c = cli_initialise(NULL)) == NULL)
300   {
301     fputs("ERROR: cli_initialize() failed...\n", stderr);
302     return (NULL);
303   }
304
305   if (!cli_connect(c, server, &ip))
306   {
307     fputs("ERROR: cli_connect() failed...\n", stderr);
308     return (NULL);
309   }
310
311   if (!cli_session_request(c, &calling, &called))
312   {
313     fputs("ERROR: cli_session_request() failed...\n", stderr);
314     return (NULL);
315   }
316
317   if (!cli_negprot(c))
318   {
319     fputs("ERROR: SMB protocol negotiation failed\n", stderr);
320     cli_shutdown(c);
321     return (NULL);
322   }
323
324  /*
325   * Do password stuff...
326   */
327
328   if (!cli_session_setup(c, username, 
329                          password, strlen(password),
330                          password, strlen(password),
331                          workgroup))
332   {
333     fprintf(stderr, "ERROR: SMB session setup failed: %s\n", cli_errstr(c));
334     return (NULL);
335   }
336
337   if (!cli_send_tconX(c, share, "?????",
338                       password, strlen(password)+1))
339   {
340     fprintf(stderr, "ERROR: SMB tree connect failed: %s\n", cli_errstr(c));
341     cli_shutdown(c);
342     return (NULL);
343   }
344
345  /*
346   * Return the new connection...
347   */
348
349   return (c);
350 }
351
352
353 /*
354  * 'smb_print()' - Queue a job for printing using the SMB protocol.
355  */
356
357 static int                              /* O - 0 = success, non-0 = failure */
358 smb_print(struct cli_state *cli,        /* I - SMB connection */
359           char             *title,      /* I - Title/job name */
360           FILE             *fp)         /* I - File to print */
361 {
362   int   fnum;           /* File number */
363   int   nbytes,         /* Number of bytes read */
364         tbytes;         /* Total bytes read */
365   char  buffer[8192],   /* Buffer for copy */
366         *ptr;           /* Pointer into tile */
367
368
369  /*
370   * Sanitize the title...
371   */
372
373   for (ptr = title; *ptr; ptr ++)
374     if (!isalnum((int)*ptr) && !isspace((int)*ptr))
375       *ptr = '_';
376
377  /*
378   * Open the printer device...
379   */
380
381   if ((fnum = cli_open(cli, title, O_RDWR | O_CREAT | O_TRUNC, DENY_NONE)) == -1)
382   {
383     fprintf(stderr, "ERROR: %s opening remote file %s\n",
384             cli_errstr(cli), title);
385     return (1);
386   }
387
388  /*
389   * Copy the file to the printer...
390   */
391
392   if (fp != stdin)
393     rewind(fp);
394
395   tbytes = 0;
396
397   while ((nbytes = fread(buffer, 1, sizeof(buffer), fp)) > 0)
398   {
399     if (cli_write(cli, fnum, 0, buffer, tbytes, nbytes) != nbytes)
400     {
401       fprintf(stderr, "ERROR: Error writing file: %s\n", cli_errstr(cli));
402       break;
403     }
404
405     tbytes += nbytes;
406   } 
407
408   if (!cli_close(cli, fnum))
409   {
410     fprintf(stderr, "ERROR: %s closing remote file %s\n",
411             cli_errstr(cli), title);
412     return (1);
413   }
414   else
415     return (0);
416 }