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