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